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
useState
for toggling modals or tracking form values. - Use
useEffect
to fetch data from an API when a component mounts. - Use
useContext
to access user authentication info across components. - Use
useReducer
to manage complex multi-step form data with validation. - Use
useMemo
to avoid recalculating filtered lists or sorting operations. - Use
useCallback
when passing callback props to memoized child components. - Use
useLayoutEffect
to measure layout before browser paint (e.g., animations or positioning).
If you found this helpful, consider supporting my work at ☕ Buy Me a Coffee.
Top comments (1)
Very intresting topic is shared. Nowadays most of the India based top Augmented Reality Services companies development team uses this in case of for toggling modals or tracking form values.