In JavaScript, functions are first-class objects. Every time a component executes its render cycle, any function declared inside that component's body is re-instantiated as a brand new object in memory:
If you pass this function down as a prop to a child component wrapped in React.memo, the child will re-render on every parent render, because React sees a different function reference every time!
useCallback?useCallback is a React hook that caches a function definition between renders. It returns the exact same function reference across renders unless one of its dependencies changes.
Consider a parent with an expensive list of items:
Now, when you click "Toggle Theme":
StudentRoster re-renders to update the theme.handleRemove retains its exact same cached reference.StudentRow checks its props: student is identical, and onRemove is identical.<StudentRow> components skip re-rendering entirely!useCallback + React.memoRemember: useCallback does not make function creation faster.
In fact, calling useCallback has a slight overhead (allocating arrays and comparing dependencies).
useCallback is only useful when:
React.memo).useEffect dependency array).useCallback hook in React?useCallback have little benefit if the child component receiving the function is NOT wrapped in React.memo?useCallback with functional state updates (setCount(prev => prev + 1)) help dependency arrays?useCallback necessary inside a useEffect workflow?useCallback(fn, deps) return?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Memoizing Components with React memo | The useMemo Hook and Expensive Computations |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.