Nearby lessons
24 of 43🪝 ReactJS – useCallback Hook
📌 What is useCallback?
What is useCallback in React?
The useCallback hook returns a memoized function.
It is useful when passing callbacks to child components that rely on reference equality
to prevent unnecessary re-renders.
The useCallback and useMemo hooks are similar:
useMemo→ returns a memoized value.useCallback→ returns a memoized function.
📌 Syntax of useCallback
const memoizedFn = useCallback(() => {
// logic here
}, [dependencies]);
- Callback Function: The function you want to memoize.
- Dependencies: The function is re-created only when dependencies change.
⚙️ Without useCallback
In this example, the Learning function is recreated every time the parent
App re-renders. This causes the child component to re-render unnecessarily
even if Learning does not change.
✅ With useCallback
Here, useCallback ensures that Learning function is
memoized. It will only re-create if dependencies change, preventing
unnecessary child re-renders.
🧮 Execution Flow of useCallback
- React renders the parent component (
App). - The
Learningfunction is created. - If
useCallbackis used, the same function reference is reused unless dependencies change. - The child component (
ChildA) receives props. - Because of
React.memo,ChildAonly re-renders if props actually change.