React useCallback Hook
⚡ React useCallback Hook
The useCallback Hook is used to memoize functions in React so that they don’t get recreated on every render.
It is mainly used for performance optimization, especially when passing functions to child components that rely on referential equality (like React.memo).
🧠 Why useCallback?
In React, every render recreates functions:
handleClickis recreated on every render.If
Childis wrapped inReact.memo, it still re-renders, because the prop reference changed.
useCallback fixes this by memoizing the function reference.
🛠 Syntax
dependencies– array of values the function depends on.Function is recreated only when dependencies change.
🧪 Example 1: Basic useCallback
🧪 Example 2: Using useCallback with React.memo
✅ Without useCallback, Child would re-render every time Parent renders.
✅ With useCallback, Child only re-renders if the function reference changes.
🧪 Example 3: useCallback with Dependencies
🧠 Key Notes
| Feature | Description |
|---|---|
| Memoizes function | ✔ |
| Reduces unnecessary re-renders | ✔ |
Useful with React.memo | ✔ |
| Dependencies array required | ✔ |
| Does not memoize return value | ❌ (use useMemo for values) |
⚡ Difference Between useCallback and useMemo
| Hook | Memoizes | Returns |
|---|---|---|
useCallback | Function | Function reference |
useMemo | Value | Computed value |
🎯 Summary
useCallbackprevents unnecessary recreation of functions.Useful for performance optimization with
React.memo.Always include proper dependencies.
Does not memoize the result — only the function itself.
