React Hooks Summary
1. useState
-
memoizedStateholds the current state value. -
baseStateis the initial state value. -
dispatchis the setter function to update state. - Triggers re-render after the current call stack is empty.
2. useEffect
- Allows you to perform side effects (API calls, subscriptions).
- Cleanup is handled by returning a function inside the effect.
- Cleanup runs:
- Before the component unmounts.
- Before the effect runs again (if dependencies change).
3. useMemo
- Caches the result of a computation.
- Prevents recalculating expensive operations unless dependencies change.
- Useful for:
- Filtering, sorting, parsing large data.
- Memoizing derived data for performance.
- Can also be used to wrap child components to prevent unnecessary re-renders (in conjunction with
React.memo).
4. React.memo vs useMemo
-
React.memo: Prevents re-rendering a component unless props change. -
useMemo: Prevents re-running a function unless dependencies change.
5. useCallback
- Memoizes the function definition itself.
- Useful when passing callbacks to memoized child components.
- Prevents unnecessary re-renders due to new function references on each render.
6. useRef
- Mutable ref object that persists for the full lifetime of the component.
- Doesn't trigger re-renders.
- Can be used to access DOM nodes or hold mutable variables.
7. useReducer
- Alternative to
useStatefor complex state logic. - Accepts a reducer function and an initial state.
- Returns
[state, dispatch]. - Best for managing state transitions or multiple sub-values.
8. useLayoutEffect
- Like
useEffect, but runs after DOM mutation, before paint. - Use for DOM measurements, layout adjustments.
- Main use case: e.g., sidebar collapse before layout shift.
9. useImperativeHandle
- Customizes the instance value exposed by
ref. - Used with
forwardRef. - Allows parent to trigger child functions imperatively.
- Use case: trigger child API call on parent submit button click.
10. useDebugValue
- Used for debugging custom hooks in React DevTools.
- Display custom hook values to help debugging.
Top comments (0)