useCallback and useReducer are two important React Hooks that help with performance optimization and state management.
useCallback
useCallback memoizes a function, meaning React will reuse the same function instance between renders unless its dependencies change.
Memoizes a function.
Prevents unnecessary function recreation.
Useful with React.memo and dependency arrays.
Why use it?
Normally, a function is recreated every time a component re-render
Every render creates a new handleClick function.
Now React reuses the same function reference.
Without useCallback:
Even though Child is wrapped with React.memo, it still re-renders because handleClick is a new function every render.
When NOT to use useCallback
Don't wrap every function in useCallback.
If the function isn't passed to memoized children or used as a dependency elsewhere, useCallback may add unnecessary complexity.
useReducer
useReducer is an alternative to useState for managing complex state logic.
Think of it like a simplified Redux inside a component.
Manages complex state using a reducer function.
State changes happen through dispatched actions.
Ideal when state logic becomes difficult to manage with multiple useState hooks
state → current state
dispatch() → sends an action
reducer() → decides how state changes
diff
| useState | useReducer |
|---|---|
| Simple state | Complex state |
| Easy to learn | More structured |
| Few state variables | Many related state values |
| Direct update | Update through actions |
| Best for simple forms/counters | Best for workflows, forms, API states |
Top comments (0)