DEV Community

Cover image for Lumping together React hooks
Ai
Ai

Posted on

Lumping together React hooks

This week at TTS, my class is learning about React hooks. One assignemnt involved watching PedroTech's react hooks course video and writing about three hooks.

This article is a "wrapper" around that assignment. I'll actually discuss all 10 prebuilt hooks albeit at a shallow level. Please let me know if I got anything wrong.


useState(), useMemo(), and useReducer()

Track state and signal DOM renders.

๐Ÿ“ useState() signals a render whenever its state changes. Use this be default.

๐Ÿ“ useMemo() signals a render based on other state dependencies you pass it. Use this when you want to memoize expensive calculations.

๐Ÿ“ useCallback() signals a render based on component-level dependencies. Also use this to memoize expensive calculations.

๐Ÿ“ useReducer() provides an API for arbitrary state-render interactions, e.g. update both state x and y when state z changes. Use this for "complicated" state-render interactions and when scaling your app is a primary concern.

useEffect() and useLayoutEffect()

Track depencies and signal "side-effects" that don't necessarily affect the DOM.

๐Ÿ“ useEffect() activates after virtual DOM updates and DOM renders. Use this by default.

๐Ÿ“ useLayoutEffect() activates after virtual DOM updates but before DOM renders. Use this when you want to "measure" DOM properties before render.

useContext()

๐Ÿ“ useContext() provides API for passing props down the component tree.

useRef() and useImperativeHandle()

๐Ÿ“ useRef() tracks real DOM elements. Use this to focus on input fields.

๐Ÿ“ useImperativeHandle() provides an API for exporting the useRef() reference to other components. Use this when your input is spread across multiple components.

useDebugValue()

๐Ÿ“ useDebugValue() provides an API for labeling custom hooks in the console output. Use this when creating a complicated custom hook.

Conclusion

React hooks are probably difficult to "learn" in isolation because they likely make more sense in a concrete React app. Moreover, it seems like its more important to learn an efficient and effective workflow using many different hooks to accomplish a particular task rather than just "learning" an individual React hook.

๐Ÿ“‘ Evan You's talk at dotJS 2019 provides great context for why we even have hooks in React as well as similar ideas in other libraries/frameworks like Vue and Svelte.


Banner source: ๐ŸŽฅ ใ„ใ—ใ‚ใŸใ‚Šๆทณๆฒป ๏ผ† ็ ‚ๅŽŸ่‰ฏๅพณ ๏ผ‹ ใ‚„ใใ—ใพใ‚‹ใˆใคใ“ใ€Œ็ฅžๆง˜ใฎใ„ใ†ใจใŠใ‚Šใ€๏ผˆ2010๏ผ‰

Article source: ๐Ÿ™๐Ÿฑ Ai-Yukino/dev.to

Discussion (0)