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

Top comments (0)