React useCallback Hook
React's useCallback Hook is a powerful tool to optimize performance and prevent unnecessary re-renders. In this guide, you’ll learn:
- What 
useCallbackdoes - When and why to use it
 - Real-world example
 - Common pitfalls and tips
 
What is useCallback?
The useCallback Hook returns a memoized version of a function.
This means the function reference will not change unless the dependencies change.
Why Use useCallback?
In React, every time a component re-renders, all its functions get recreated. This causes problems if:
- You're passing functions as props to child components
 - Those child components rely on React.memo to avoid re-renders
 
Using useCallback ensures that the function keeps the same reference unless its dependencies actually change.
Problem: Unwanted Re-Renders
Let’s look at an example without useCallback.
index.js
Todos.js
🔄 Try it out
Click the Count + button. Notice how Todos re-renders even though todos didn’t change?
Why Is This Happening?
This is due to referential equality.
Every re-render of App creates a new version of the addTodo function, even if its logic is identical.
So React.memo sees a new function and re-renders the Todos component.
Solution: useCallback
Wrap the function with useCallback to preserve the reference:
index.js (fixed)
Now what happens?
Now when you click the Count + button:
✅ The Todos component does not re-render ✅ addTodo has the same reference ✅ Performance is improved
Gotcha: Dependency Array
Be careful with what you include in the dependency array.
💡 If you use the updater function (setTodos(prev => ...)), you can often pass an empty array:
Summary
useCallbackhelps prevent unnecessary re-renders- It memorizes the function so its reference doesn’t change
 - Ideal when passing functions to 
React.memocomponents - Use with care—always manage the dependency array properly