This content originally appeared on DEV Community and was authored by davinceleecode
React provides powerful hooks that allow you to manage state, side effects, performance optimizations, and much more — all inside functional components. Here’s a concise guide on when to use each hook:
| Hook | Use Case |
|---|---|
useState |
Manage local component state (e.g., input fields, toggles, counters) |
useEffect |
Perform side effects (e.g., data fetching, subscriptions, timers) |
useContext |
Access shared/global state without prop drilling (e.g., theme, auth) |
useRef |
Reference DOM elements or store mutable values across renders |
useReducer |
Manage complex state logic or state transitions (e.g., form wizard, cart) |
useMemo |
Optimize performance by memoizing expensive calculations |
useCallback |
Memoize functions to prevent unnecessary re-renders |
useLayoutEffect |
Execute synchronously after DOM changes but before browser paint |
Example Use Cases:
- Use
useStatefor toggling modals or tracking form values. - Use
useEffectto fetch data from an API when a component mounts. - Use
useContextto access user authentication info across components. - Use
useReducerto manage complex multi-step form data with validation. - Use
useMemoto avoid recalculating filtered lists or sorting operations. - Use
useCallbackwhen passing callback props to memoized child components. - Use
useLayoutEffectto measure layout before browser paint (e.g., animations or positioning).
If you found this helpful, consider supporting my work at
Buy Me a Coffee.
This content originally appeared on DEV Community and was authored by davinceleecode