-
Notifications
You must be signed in to change notification settings - Fork 3
/
1939c755.308154dd.js
1 lines (1 loc) · 9.91 KB
/
1939c755.308154dd.js
1
(window.webpackJsonp=window.webpackJsonp||[]).push([[9],{134:function(e,t,n){"use strict";n.d(t,"a",(function(){return b})),n.d(t,"b",(function(){return d}));var a=n(0),c=n.n(a);function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function l(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?o(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):o(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function u(e,t){if(null==e)return{};var n,a,c=function(e,t){if(null==e)return{};var n,a,c={},r=Object.keys(e);for(a=0;a<r.length;a++)n=r[a],t.indexOf(n)>=0||(c[n]=e[n]);return c}(e,t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);for(a=0;a<r.length;a++)n=r[a],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(c[n]=e[n])}return c}var s=c.a.createContext({}),i=function(e){var t=c.a.useContext(s),n=t;return e&&(n="function"==typeof e?e(t):l(l({},t),e)),n},b=function(e){var t=i(e.components);return c.a.createElement(s.Provider,{value:t},e.children)},p={inlineCode:"code",wrapper:function(e){var t=e.children;return c.a.createElement(c.a.Fragment,{},t)}},m=c.a.forwardRef((function(e,t){var n=e.components,a=e.mdxType,r=e.originalType,o=e.parentName,s=u(e,["components","mdxType","originalType","parentName"]),b=i(n),m=a,d=b["".concat(o,".").concat(m)]||b[m]||p[m]||r;return n?c.a.createElement(d,l(l({ref:t},s),{},{components:n})):c.a.createElement(d,l({ref:t},s))}));function d(e,t){var n=arguments,a=t&&t.mdxType;if("string"==typeof e||a){var r=n.length,o=new Array(r);o[0]=m;var l={};for(var u in t)hasOwnProperty.call(t,u)&&(l[u]=t[u]);l.originalType=e,l.mdxType="string"==typeof e?e:a,o[1]=l;for(var s=2;s<r;s++)o[s]=n[s];return c.a.createElement.apply(null,o)}return c.a.createElement.apply(null,n)}m.displayName="MDXCreateElement"},158:function(e,t,n){"use strict";n.r(t),t.default=n.p+"assets/images/react-hooks-cheat-sheet-97aa08c28454a1ac8a861e4eb6436cd5.png"},74:function(e,t,n){"use strict";n.r(t),n.d(t,"frontMatter",(function(){return o})),n.d(t,"metadata",(function(){return l})),n.d(t,"rightToc",(function(){return u})),n.d(t,"default",(function(){return i}));var a=n(3),c=n(7),r=(n(0),n(134)),o={slug:"react-hooks-cheat-sheet",title:"React Hooks Cheat Sheet",author:"Bunlong",author_title:"React Patterns Team",author_url:"https://github.com/Bunlong",author_image_url:"https://avatars1.githubusercontent.com/u/37023003?s=400&u=0049c6773040efb265cdf622076305f8b47facec&v=4",tags:["hook"],image:"/img/react-hooks-cheat-sheet.png"},l={permalink:"/blog/react-hooks-cheat-sheet",source:"@site/blog/2021-07-29-react-hooks-cheat-sheet.md",description:"React Hooks Cheat Sheet",date:"2021-07-29T00:00:00.000Z",tags:[{label:"hook",permalink:"/blog/tags/hook"}],title:"React Hooks Cheat Sheet",readingTime:2.335,truncated:!0,nextItem:{title:"What is React Server Component",permalink:"/blog/react-server-component"}},u=[{value:"State Management",id:"state-management",children:[{value:"useState()",id:"usestate",children:[]}]},{value:"Side Effects",id:"side-effects",children:[{value:"useEffect()",id:"useeffect",children:[]}]},{value:"Memoize a Callback",id:"memoize-a-callback",children:[{value:"useCallback()",id:"usecallback",children:[]}]},{value:"Memoize a Value",id:"memoize-a-value",children:[{value:"useMemo()",id:"usememo",children:[]}]},{value:"Reference Element",id:"reference-element",children:[{value:"userRef()",id:"userref",children:[]}]},{value:"Context API",id:"context-api",children:[{value:"useContext()",id:"usecontext",children:[]}]},{value:"Manage State",id:"manage-state",children:[{value:"useReducer()",id:"usereducer",children:[]}]},{value:"Create Your Own Custom Hook",id:"create-your-own-custom-hook",children:[]}],s={rightToc:u};function i(e){var t=e.components,o=Object(c.a)(e,["components"]);return Object(r.b)("wrapper",Object(a.a)({},s,o,{components:t,mdxType:"MDXLayout"}),Object(r.b)("p",null,Object(r.b)("img",{alt:"React Hooks Cheat Sheet",src:n(158).default,title:"React Hooks Cheat Sheet"})),Object(r.b)("h2",{id:"state-management"},"State Management"),Object(r.b)("h3",{id:"usestate"},"useState()"),Object(r.b)("p",null,"Declare state."),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"const [name, setName] = useState('Initial value');\n")),Object(r.b)("p",null,"Update state."),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"setName('New value'); // directly\n")),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"setName((value) => 'New' + value); // based on previous state\n")),Object(r.b)("h2",{id:"side-effects"},"Side Effects"),Object(r.b)("h3",{id:"useeffect"},"useEffect()"),Object(r.b)("p",null,"Triggers callback function only once when component is mounted."),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"useEffect( () => {\n // Side effects, HTTP request, setTimeout, ... etc.\n}, []);\n")),Object(r.b)("p",null,"Triggers callback function when dependency 'VALUE' is changed."),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"useEffect(() => {\n // Side effects, HTTP request, setTimeout, ... etc.\n}, [value]);\n")),Object(r.b)("p",null,"Cleanup side effects when component is unmounted."),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"useEffect(() => {\n let timeout = setTimeout(doSomething, 5000);\n return () => clearTimeout(timeout);\n}, [value]);\n")),Object(r.b)("h2",{id:"memoize-a-callback"},"Memoize a Callback"),Object(r.b)("h3",{id:"usecallback"},"useCallback()"),Object(r.b)("p",null,"Return new function only when dependencies change."),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"const handleClick = useCallback(() => {\n doSomethingWith(param1, param2);\n}, [param1, param2]);\n")),Object(r.b)("p",null,"Memoize callback for a dynamic list of elements."),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"const handleClick = useCallback((event) => {\n const button = event.target;\n const value = button.getAttribute('data-value');\n doSomethingWith(value);\n}, []);\n\n<ul>\n {objects.map((obj) => (\n <li key={obj.id}>\n <button data-value={obj.value} onClick={handleClick}>\n {obj.value}\n </button>\n </li>\n ))}\n</ul>\n")),Object(r.b)("h2",{id:"memoize-a-value"},"Memoize a Value"),Object(r.b)("h3",{id:"usememo"},"useMemo()"),Object(r.b)("p",null,"Will trigger only when dependencies change."),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"const value = useMemo(() => {\n // evaluates only when param1 or param2 change\n return expensiveOperation(param1, param2);\n}, [param1, param2]);\n")),Object(r.b)("h2",{id:"reference-element"},"Reference Element"),Object(r.b)("h3",{id:"userref"},"userRef()"),Object(r.b)("p",null,'userRef is like a "BOX" that can hold a mutable value in its current property.'),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),'const inputRef = useRef(null); // initialize\n...\nconst onButtonClick = () => {\n // current points to input element\n inputRef.current.focus(); // get reference\n}\n\n<input type="text" placeholder="Name" ref={inputRef} />\n<button onClick={onButtonClick}>Focus input</button>\n')),Object(r.b)("h2",{id:"context-api"},"Context API"),Object(r.b)("h3",{id:"usecontext"},"useContext()"),Object(r.b)("p",null,"Avoid props drilling using context API."),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"// create and export context\nexport const ThemeContext = createContext(null);\n\n// wrap parent component with context provider\nreturn (\n <ThemeContext.Provider value={{theme: 'dark}}>\n <App />\n </ThemeContext.Provider>\n);\n\n// use context inside any child component\nconst { theme } = useContext(ThemeContext);\n")),Object(r.b)("h2",{id:"manage-state"},"Manage State"),Object(r.b)("h3",{id:"usereducer"},"useReducer()"),Object(r.b)("p",null,"Initialize a local state and create reducer."),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"const initialState = {\n value: 0\n};\n\nconst reducer = (state, action) {\n switch (action.type) {\n case 'increment':\n return { ...state, value: state.value + 1 };\n case 'set_to':\n return { ...state, value: state.value };\n default:\n throw new Error('Unhandled action');\n }\n};\n")),Object(r.b)("p",null,"Create local state and dispatch actions."),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"const [state, dispatch] = useReducer(reducer, initialState);\n...\n<button onClick={() => dispatch({ type: 'increment' })} />\n<button onClick={() => dispatch({ type: 'set_to', value: 24 })} />\n<button><button>\n")),Object(r.b)("h2",{id:"create-your-own-custom-hook"},"Create Your Own Custom Hook"),Object(r.b)("p",null,"Custom hooks must start with ",Object(r.b)("inlineCode",{parentName:"p"},"use"),"."),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-js"}),"const useApiResult = (param) => {\n const [result, setResult] = useState(null);\n useEffect(() => {\n // your tasks\n }, [param]);\n return { result };\n};\n\n// to use it in a component\nconst { result } = useApiResult('some-param');\n")))}i.isMDXComponent=!0}}]);