1. What is useCallback?
useCallback is a React Hook used to remember a function between renders.
In simple terms:
useCallbackprevents React from creating a new function object on every render, as long as its dependencies have not changed.
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
Here, React remembers the handleClick function.
On future renders:
- If dependencies are unchanged → React gives you the same function
- If dependencies change → React creates and returns a new function
2. Why do we need useCallback?
First, understand a common React behavior.
Consider:
function App() {
const handleClick = () => {
console.log("Clicked");
};
return <button onClick={handleClick}>Click</button>;
}
Every time App renders, this function is created again:
Render 1
↓
handleClick → Function A
Render 2
↓
handleClick → Function B
Render 3
↓
handleClick → Function C
Even though the function code looks exactly the same, Function A, Function B, and Function C are different function objects.
This normally doesn't matter.
But it becomes important when you pass that function to a memoized child component.
3. The main reason for useCallback
The most important use case is:
Parent
↓
function prop
↓
Memoized Child
For example:
const Child = React.memo(({ onClick }) => {
console.log("Child rendered");
return <button onClick={onClick}>Click</button>;
});
Now the parent:
function Parent() {
const [count, setCount] = useState(0);
const handleClick = () => {
console.log("Clicked");
};
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<Child onClick={handleClick} />
</>
);
}
When count changes:
Parent renders
↓
new handleClick function
↓
Child receives different function reference
↓
Child renders again
Even though Child doesn't actually need to render again.
useCallback can solve this:
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
Now:
Parent renders
↓
useCallback returns same function
↓
Child receives same function reference
↓
React.memo can skip Child rendering
This is the most important concept to understand about useCallback.
4. useCallback syntax
The basic syntax is:
const memoizedFunction = useCallback(function, dependencies);
For example:
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
There are two important parts:
Function
() => {
console.log("Clicked");
}
Dependency array
[]
Together:
useCallback(() => {
console.log("Clicked");
}, []);
5. What does useCallback actually remember?
This is an important point.
useCallback does not remember the result of a function.
It remembers the function itself.
For example:
const calculate = useCallback(() => {
return 10 + 20;
}, []);
React remembers:
calculate → function reference
It does not primarily cache:
calculate → 30
That is the job of useMemo.
So:
useCallback → remembers a function
useMemo → remembers a calculated value
6. useCallback vs useMemo
This is one of the most common interview questions.
useCallback
const handleClick = useCallback(() => {
console.log("Hello");
}, []);
It returns a function.
useMemo
const total = useMemo(() => {
return price * quantity;
}, [price, quantity]);
It returns a calculated value.
Think of it like this:
useCallback
↓
"I want to remember this function"
useMemo
↓
"I want to remember this calculated value"
You can think of:
useCallback(fn, dependencies)
as roughly related to:
useMemo(() => fn, dependencies)
Conceptually, useCallback is the convenient Hook specifically designed for memoizing function references.
7. Basic useCallback example
Let's start with a very simple example.
import { useCallback, useState } from "react";
function App() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Button clicked");
}, []);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={handleClick}>
Click Me
</button>
</div>
);
}
Here:
const handleClick = useCallback(() => {
console.log("Button clicked");
}, []);
The empty dependency array means:
"This callback doesn't depend on any changing value."
Therefore React can reuse the same function reference between renders.
8. Does useCallback prevent re-rendering?
No.
This is a very important point.
useCallback does not prevent the component containing it from rendering.
For example:
function App() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
return (
<button onClick={() => setCount(count + 1)}>
{count}
</button>
);
}
When count changes:
count changes
↓
App renders again
↓
useCallback runs
↓
same function reference is returned
The parent still renders.
useCallback only helps when function identity/reference matters, particularly with memoized children or other dependency-based Hooks.
9. Understanding function identity
This is the key concept behind useCallback.
Consider:
const fn1 = () => {};
const fn2 = () => {};
Even though they look identical:
fn1 === fn2
is:
false
Every new function expression creates a new function object.
In React:
function App() {
const handleClick = () => {};
}
When App renders again:
First render:
handleClick → Function A
Second render:
handleClick → Function B
A !== B
With:
const handleClick = useCallback(() => {}, []);
React can preserve the function reference:
First render:
handleClick → Function A
Second render:
handleClick → Function A
Third render:
handleClick → Function A
provided the dependencies haven't changed.
10. useCallback with React.memo
This is the most practical pattern.
Without useCallback
import { memo, useState } from "react";
const Child = memo(({ onClick }) => {
console.log("Child rendered");
return (
<button onClick={onClick}>
Child Button
</button>
);
});
function App() {
const [count, setCount] = useState(0);
const handleClick = () => {
console.log("Hello");
};
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<Child onClick={handleClick} />
</>
);
}
You might expect React.memo to prevent the child from rendering.
But:
Parent renders
↓
new handleClick function
↓
Child receives new function reference
↓
memo sees changed prop
↓
Child renders
11. With useCallback
import { memo, useCallback, useState } from "react";
const Child = memo(({ onClick }) => {
console.log("Child rendered");
return (
<button onClick={onClick}>
Child Button
</button>
);
});
function App() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Hello");
}, []);
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<Child onClick={handleClick} />
</>
);
}
Now:
Parent renders
↓
useCallback returns same function
↓
Child receives same function reference
↓
React.memo sees same props
↓
Child does not re-render
This is where useCallback becomes useful.
12. Important: useCallback and React.memo often work together
A very common pattern is:
const Child = React.memo(ChildComponent);
const handleClick = useCallback(() => {
// logic
}, []);
Then:
<Child onClick={handleClick} />
Think:
React.memo
↓
"Don't render child if props haven't changed"
useCallback
↓
"Keep function prop reference stable"
Together:
Parent
↓
useCallback
↓
stable function reference
↓
React.memo
↓
Child can skip unnecessary rendering
13. useCallback with dependencies
Now suppose the callback uses a changing value.
function App() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log(count);
}, [count]);
return (
<button onClick={handleClick}>
Click
</button>
);
}
Here the callback depends on:
count
Therefore:
[count]
must be included.
The behavior is:
count = 0
↓
callback remembers count = 0
count changes to 1
↓
dependency changed
↓
new callback created
↓
new function sees count = 1
This is important because the callback needs the latest value.
14. Why dependency arrays matter
Consider:
const handleClick = useCallback(() => {
console.log(count);
}, []);
This looks harmless, but it is wrong if you expect the callback to always use the latest count.
The callback has captured the value from the render in which it was created.
For example:
Initial render
count = 0
↓
callback remembers count = 0
count becomes 1
↓
component renders
callback is still the old callback
↓
callback may see count = 0
This is related to closures and stale values.
Correct:
const handleClick = useCallback(() => {
console.log(count);
}, [count]);
15. Example: Counter
function Counter() {
const [count, setCount] = useState(0);
const showCount = useCallback(() => {
console.log(`Current count: ${count}`);
}, [count]);
return (
<>
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={showCount}>
Show Count
</button>
</>
);
}
Flow:
count = 0
↓
showCount remembers count = 0
count = 1
↓
[count] changed
↓
new showCount
↓
showCount remembers count = 1
16. useCallback with state updater functions
Sometimes you can avoid adding state to dependencies by using the functional state updater.
Instead of:
const addItem = useCallback(() => {
setItems([...items, newItem]);
}, [items]);
you can write:
const addItem = useCallback(() => {
setItems(items => [...items, newItem]);
}, [newItem]);
Why?
Because:
items => [...items, newItem]
receives the latest state from React.
This can reduce dependencies.
Flow
Button clicked
↓
setItems(updater function)
↓
React provides latest items
↓
new array created
↓
state updated
This is a very useful real-world pattern.
17. Example: Todo list
function TodoApp() {
const [todos, setTodos] = useState([]);
const addTodo = useCallback((todo) => {
setTodos(prevTodos => [
...prevTodos,
todo
]);
}, []);
return (
<TodoForm onAdd={addTodo} />
);
}
Notice:
setTodos(prevTodos => ...)
Because we're using the updater form, we don't need:
[todos]
as a dependency.
This allows:
addTodo
to remain stable.
18. useCallback with child components
Imagine a product page:
ProductPage
|
+-- ProductList
|
+-- ProductCard
|
+-- CartButton
Suppose:
<ProductCard onAddToCart={handleAddToCart} />
If the parent frequently renders, a new handleAddToCart function can be created each time.
You can use:
const handleAddToCart = useCallback((product) => {
// add product
}, []);
Then:
<ProductCard
product={product}
onAddToCart={handleAddToCart}
/>
If ProductCard is memoized:
const ProductCard = React.memo(...);
the stable callback can help it skip unnecessary renders.
19. useCallback with event handlers
A very common example:
const handleDelete = useCallback((id) => {
deleteProduct(id);
}, []);
Then:
<Product
onDelete={handleDelete}
/>
The callback can remain stable.
This is useful when the handler is passed through multiple components.
20. useCallback with lists
Suppose:
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "David" },
{ id: 3, name: "Sarah" }
];
You have:
function UserList() {
const handleDelete = useCallback((id) => {
console.log("Delete:", id);
}, []);
return (
<>
{users.map(user => (
<UserItem
key={user.id}
user={user}
onDelete={handleDelete}
/>
))}
</>
);
}
All UserItem components receive the same function reference:
UserItem 1 → handleDelete A
UserItem 2 → handleDelete A
UserItem 3 → handleDelete A
rather than:
UserItem 1 → function A
UserItem 2 → function B
UserItem 3 → function C
This can be valuable when the list is large and items are memoized.
21. Important difference: callback inside map
Consider:
{users.map(user => (
<UserItem
key={user.id}
onDelete={() => handleDelete(user.id)}
/>
))}
Every render creates new functions:
User 1 → new function
User 2 → new function
User 3 → new function
Even if:
handleDelete
is memoized.
This is because:
() => handleDelete(user.id)
itself creates a new function.
For large lists, you may instead pass the stable handler:
<UserItem
key={user.id}
user={user}
onDelete={handleDelete}
/>
and let the child call:
onDelete(user.id);
This avoids creating a separate callback for every item.
22. useCallback with Context API
This is another important real-world scenario.
Suppose you have:
const AuthContext = createContext(null);
And:
function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const login = useCallback((userData) => {
setUser(userData);
}, []);
const logout = useCallback(() => {
setUser(null);
}, []);
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
}
Here login and logout are stable functions.
But there is another issue:
value={{ user, login, logout }}
creates a new object every render.
So you may also use useMemo:
const value = useMemo(() => ({
user,
login,
logout
}), [user, login, logout]);
Then:
<AuthContext.Provider value={value}>
This gives:
useCallback
↓
memoize functions
useMemo
↓
memoize context value object
This is a common combination.
23. useCallback with useEffect
This is another important area.
Consider:
function Search({ query }) {
const fetchData = () => {
console.log("Fetching:", query);
};
useEffect(() => {
fetchData();
}, [fetchData]);
}
This creates a problem.
Every render:
new fetchData function
↓
fetchData changed
↓
useEffect runs
↓
new render
↓
new fetchData
Potentially causing repeated effect execution.
One solution is:
const fetchData = useCallback(() => {
console.log("Fetching:", query);
}, [query]);
useEffect(() => {
fetchData();
}, [fetchData]);
Now:
query unchanged
↓
same fetchData reference
↓
effect doesn't needlessly rerun
If query changes:
query changes
↓
new fetchData
↓
effect sees dependency changed
↓
effect runs
24. But don't automatically use useCallback with useEffect
Sometimes the better solution is to move the function directly inside the effect.
Instead of:
const fetchData = useCallback(() => {
console.log(query);
}, [query]);
useEffect(() => {
fetchData();
}, [fetchData]);
you can often write:
useEffect(() => {
console.log(query);
}, [query]);
This is simpler.
Therefore:
Don't use
useCallbackjust because a function is used insideuseEffect.
Use it when function identity actually needs to be stable.
25. useCallback with custom Hooks
Suppose you create:
function useCounter() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(prev => prev + 1);
}, []);
return {
count,
increment
};
}
Component:
function App() {
const { count, increment } = useCounter();
return (
<>
<h2>{count}</h2>
<button onClick={increment}>
Increment
</button>
</>
);
}
The custom Hook exposes a stable function:
useCounter
↓
count
increment
↓
Component
This is useful when building reusable application logic.
26. useCallback with API calls
Consider a search page:
function SearchPage() {
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);
const searchProducts = useCallback(async () => {
if (!query) return;
const response = await fetch(
`/api/products?search=${query}`
);
const data = await response.json();
setResults(data);
}, [query]);
return (
<>
<input
value={query}
onChange={e => setQuery(e.target.value)}
/>
<button onClick={searchProducts}>
Search
</button>
</>
);
}
Here searchProducts depends on:
query
Therefore:
[query]
is required.
When query changes:
query changes
↓
SearchPage renders
↓
useCallback sees changed query
↓
new searchProducts function
↓
click Search
↓
API called using latest query
27. useCallback does NOT make API calls faster
This is a common misunderstanding.
useCallback does not optimize:
API response time
Database query
Network latency
Server processing
It only optimizes function identity/reference stability.
So:
useCallback(fetchData, [])
does not mean:
"The API request is cached."
It means:
"The function reference is preserved."
28. useCallback with expensive child components
Suppose:
const ExpensiveComponent = React.memo(({ onAction }) => {
// expensive rendering
});
Parent:
function App() {
const [count, setCount] = useState(0);
const handleAction = useCallback(() => {
console.log("Action");
}, []);
return (
<>
<button onClick={() => setCount(count + 1)}>
{count}
</button>
<ExpensiveComponent onAction={handleAction} />
</>
);
}
Now changing count does not necessarily force ExpensiveComponent to render because:
count changes
↓
Parent renders
↓
handleAction remains same
↓
memoized child receives same props
↓
Child can skip rendering
This is one of the strongest practical reasons to use useCallback.
29. useCallback with multiple dependencies
You can have multiple dependencies:
const handleSubmit = useCallback(() => {
submitOrder(userId, productId, quantity);
}, [userId, productId, quantity]);
React checks:
userId
productId
quantity
If none changed:
same callback
If any changed:
new callback
For example:
userId = 10
productId = 50
quantity = 2
↓
userId changes to 11
↓
dependency changed
↓
new callback
30. useCallback with objects
Be careful with objects.
Suppose:
const options = {
sort: "price",
order: "asc"
};
Then:
const search = useCallback(() => {
fetchProducts(options);
}, [options]);
The problem is that options itself may be recreated on every render:
Render 1
options → Object A
Render 2
options → Object B
Render 3
options → Object C
Therefore:
[options]
keeps changing.
You may need useMemo for the object:
const options = useMemo(() => ({
sort: "price",
order: "asc"
}), []);
Then:
const search = useCallback(() => {
fetchProducts(options);
}, [options]);
But again, don't optimize unnecessarily. Often the simpler solution is better.
31. useCallback and stale closures
This is one of the most important problems to understand.
Consider:
const handleClick = useCallback(() => {
console.log(count);
}, []);
If count changes, this callback doesn't automatically update because you told React:
[]
meaning:
"This callback has no changing dependencies."
Therefore it can hold an old value.
This is called a stale closure.
Correct:
const handleClick = useCallback(() => {
console.log(count);
}, [count]);
Or sometimes use a state updater:
const increment = useCallback(() => {
setCount(prev => prev + 1);
}, []);
32. useCallback and closures
Remember that JavaScript functions create closures.
Example:
function App() {
const [count, setCount] = useState(0);
const showCount = () => {
console.log(count);
};
}
The function can access:
count
from the render where the function was created.
useCallback doesn't remove this behavior.
It controls whether React reuses the function reference.
So:
Closure
↓
Function remembers values from its render
useCallback
↓
Controls when that function reference is replaced
Understanding this makes useCallback much easier.
33. useCallback with useRef
You can combine them.
const inputRef = useRef(null);
const focusInput = useCallback(() => {
inputRef.current?.focus();
}, []);
Then:
<input ref={inputRef} />
<button onClick={focusInput}>
Focus
</button>
Here:
useRef
↓
remembers DOM element
useCallback
↓
remembers function that accesses it
This can be useful when the callback is passed to a memoized child.
34. useCallback with event listeners
Suppose you're interacting with browser APIs:
const handleResize = useCallback(() => {
console.log(window.innerWidth);
}, []);
useEffect(() => {
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, [handleResize]);
The stable callback makes the event listener setup predictable.
When dependencies don't change:
same handleResize
↓
effect dependency unchanged
↓
listener isn't unnecessarily replaced
35. useCallback with debounce logic
Search boxes are a common real-world scenario.
For example:
const handleSearch = useCallback(
debounce((value) => {
searchProducts(value);
}, 500),
[]
);
The important idea is that the debounced function itself needs a stable identity.
Otherwise a new debounce function can be created on every render, which can break the debounce behavior.
This is a more advanced use case and usually requires careful cleanup as well.
36. TypeScript: Basic useCallback
In TypeScript:
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
Usually TypeScript can infer the function type automatically.
You generally don't need to explicitly write:
const handleClick: () => void = ...
unless there is a specific reason.
37. TypeScript with parameters
const handleDelete = useCallback((id: number) => {
console.log("Deleting:", id);
}, []);
Here:
id → number
and the return type is inferred as:
void
38. TypeScript with return value
const calculateTotal = useCallback(
(price: number, quantity: number): number => {
return price * quantity;
},
[]
);
Usage:
const total = calculateTotal(100, 3);
Result:
300
However, if you're using useCallback only to cache a calculation, ask whether useMemo would be more appropriate.
39. TypeScript with a child component
type ChildProps = {
onDelete: (id: number) => void;
};
const Child = React.memo(({ onDelete }: ChildProps) => {
return (
<button onClick={() => onDelete(10)}>
Delete
</button>
);
});
Parent:
const handleDelete = useCallback((id: number) => {
console.log("Delete:", id);
}, []);
Then:
<Child onDelete={handleDelete} />
This is a common TypeScript + React pattern.
40. useCallback in a form
Consider a reusable form:
function UserForm() {
const [name, setName] = useState("");
const handleSubmit = useCallback(
(e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
console.log("Submitting:", name);
},
[name]
);
return (
<form onSubmit={handleSubmit}>
<input
value={name}
onChange={e => setName(e.target.value)}
/>
<button type="submit">
Submit
</button>
</form>
);
}
Because:
handleSubmit
uses:
name
we include:
[name]
41. useCallback with a custom button
Suppose you have:
const MyButton = React.memo(
({ onClick }: { onClick: () => void }) => {
console.log("Button rendered");
return (
<button onClick={onClick}>
Save
</button>
);
}
);
Parent:
function App() {
const [count, setCount] = useState(0);
const save = useCallback(() => {
console.log("Saving...");
}, []);
return (
<>
<button onClick={() => setCount(count + 1)}>
{count}
</button>
<MyButton onClick={save} />
</>
);
}
The save function remains stable.
Therefore MyButton can avoid unnecessary rendering when only count changes.
42. When should you use useCallback?
Use it when there is a real reason to stabilize a function reference.
Common situations:
1. Function passed to React.memo child
<Child onClick={handleClick} />
2. Function is a dependency of another Hook
useEffect(() => {
...
}, [handleSomething]);
3. Custom Hook returns functions
return {
data,
refresh,
update
};
where refresh and update should have stable identities.
4. Large component trees
When function props are passed through optimized components.
5. Expensive child rendering
When avoiding unnecessary child renders provides a measurable benefit.
43. When should you NOT use useCallback?
This is equally important.
Don't write:
const handleClick = useCallback(() => {
console.log("Hello");
}, []);
everywhere just because you can.
For a simple component:
function Button() {
const handleClick = () => {
console.log("Hello");
};
return <button onClick={handleClick}>Click</button>;
}
This is perfectly fine.
Adding useCallback may provide no meaningful benefit.
44. useCallback has a cost
useCallback isn't free.
React has to:
store callback
compare dependencies
manage Hook state
return previous/new function
Therefore:
Normal function
↓
simple
useCallback
↓
additional React bookkeeping
You should use it when the optimization actually matters.
45. Don't use useCallback for every function
Bad pattern:
const a = useCallback(() => {}, []);
const b = useCallback(() => {}, []);
const c = useCallback(() => {}, []);
const d = useCallback(() => {}, []);
const e = useCallback(() => {}, []);
If none of these functions are benefiting from stable identity, this adds unnecessary complexity.
Better:
const a = () => {};
const b = () => {};
const c = () => {};
Use useCallback when you have a reason.
46. useCallback does not automatically improve performance
This is a major interview point.
Wrong understanding:
"If I use
useCallback, my application becomes faster."
Correct understanding:
"
useCallbackcan prevent unnecessary work caused by changing function references."
For example:
Parent render
↓
new function
↓
memoized child sees changed prop
↓
child renders unnecessarily
useCallback can break that chain:
Parent render
↓
same callback reference
↓
memoized child sees same prop
↓
child can skip render
47. useCallback vs normal function
| Normal function | useCallback |
|---|---|
| New function may be created on each render | Function reference can be reused |
| Simple | More complex |
| No dependency array | Uses dependency array |
| Usually preferred by default | Use when needed |
| No memoization overhead | Has Hook/dependency overhead |
| Fine for most event handlers | Useful for stable function props |
The key is:
Use normal functions by default. Use
useCallbackfor a specific optimization or identity requirement.
48. useCallback vs useMemo
useCallback |
useMemo |
|
|---|---|---|
| Purpose | Memoize function | Memoize value |
| Returns | Function | Value |
| Example | Event handler | Calculated result |
| Main use | Stable function reference | Avoid expensive recalculation |
Example:
const handleClick = useCallback(() => {
doSomething();
}, []);
versus:
const total = useMemo(() => {
return price * quantity;
}, [price, quantity]);
49. useCallback vs useRef
These are also different.
useCallback
const fn = useCallback(() => {
console.log("Hello");
}, []);
Purpose:
Keep function reference stable
useRef
const ref = useRef(null);
Purpose:
Keep a mutable value/reference between renders
So:
useCallback → stable function
useRef → persistent mutable reference
50. A complete practical example
Consider a product management page:
ProductPage
|
+-- SearchBox
|
+-- ProductList
|
+-- ProductItem
+-- ProductItem
+-- ProductItem
Parent:
function ProductPage() {
const [search, setSearch] = useState("");
const [products, setProducts] = useState([]);
const deleteProduct = useCallback((id) => {
setProducts(prev =>
prev.filter(product => product.id !== id)
);
}, []);
return (
<>
<input
value={search}
onChange={e => setSearch(e.target.value)}
/>
<ProductList
products={products}
onDelete={deleteProduct}
/>
</>
);
}
Memoized child:
const ProductList = React.memo(
({ products, onDelete }) => {
return (
<>
{products.map(product => (
<ProductItem
key={product.id}
product={product}
onDelete={onDelete}
/>
))}
</>
);
}
);
Now:
Search changes
↓
ProductPage renders
↓
deleteProduct reference remains same
↓
ProductList receives same onDelete reference
↓
If its other props are unchanged,
React.memo can skip unnecessary rendering
This is a realistic reason to use useCallback.
51. Important point about useCallback and React Compiler
Modern React development also includes compiler-based optimization.
React's compiler can automatically optimize certain values and functions, reducing the need to manually add useCallback everywhere.
So don't treat:
useCallback()
as something that must appear throughout every React application.
The modern mindset is:
Write clear React code first, then use memoization where it is actually useful or where your project's compiler/configuration and performance strategy call for it.
52. Common mistakes
Mistake 1: Using useCallback everywhere
const handleClick = useCallback(() => {
}, []);
for every function is unnecessary.
Mistake 2: Incorrect dependency array
Wrong:
const handleClick = useCallback(() => {
console.log(count);
}, []);
Better:
const handleClick = useCallback(() => {
console.log(count);
}, [count]);
Mistake 3: Thinking it prevents parent renders
It doesn't.
useCallback
↓
stable function reference
NOT
useCallback
↓
no component render
Mistake 4: Thinking it caches API results
It doesn't.
useCallback(fetchData, [])
does not cache:
API response
It memoizes:
function reference
Mistake 5: Using useCallback without React.memo
Sometimes it can still be useful for Hook dependencies or custom Hook APIs, but the common parent-child optimization is:
useCallback + React.memo
Without a consumer that cares about function identity, the benefit may be negligible.
53. A simple mental model
Remember this:
Every render
↓
Functions can be recreated
↓
New function reference
↓
Child may think "my prop changed"
↓
Child may render
useCallback:
Every render
↓
Check dependencies
↓
Dependencies unchanged?
↓
YES
↓
Return old function
If dependencies changed:
Dependencies changed
↓
Create new function
↓
Return new function
54. The most important example to remember
If you remember only one example, remember this:
const Child = React.memo(({ onClick }) => {
console.log("Child rendered");
return <button onClick={onClick}>Click</button>;
});
function Parent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Hello");
}, []);
return (
<>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
<Child onClick={handleClick} />
</>
);
}
The important relationship is:
useCallback
↓
stable function reference
↓
React.memo
↓
child can skip unnecessary rendering
55. Interview-focused questions
What is useCallback?
useCallback is a React Hook that memoizes a function reference so React can reuse the same function between renders when its dependencies haven't changed.
Why use useCallback?
Mainly to prevent unnecessary re-renders of memoized child components when a function is passed as a prop.
Does useCallback prevent component re-rendering?
No. It only stabilizes the function reference.
Does useCallback cache function results?
No. useMemo is used to memoize calculated values.
When does useCallback create a new function?
When one or more dependencies change.
What happens with []?
React can reuse the same callback reference across renders, assuming the callback doesn't need changing reactive values.
What is a stale closure?
A callback can retain values from an older render when its dependencies are incorrectly specified.
Can useCallback be used without React.memo?
Yes, but the benefit is often limited unless something else depends on the function's identity.
Is useCallback always good for performance?
No. It has its own overhead and should be used when it provides a meaningful benefit.
useCallback vs useMemo?
useCallback → memoizes function
useMemo → memoizes value
56. Important points to remember
1. useCallback remembers a function reference.
2. It does NOT remember the function's result.
3. It does NOT stop the parent component from rendering.
4. It is most useful when function identity matters.
5. React.memo + useCallback is a common optimization pattern.
6. Dependencies are critical.
7. Missing dependencies can cause stale values.
8. State updater functions can reduce dependencies.
9. Don't use useCallback for every function.
10. useCallback does not cache API responses.
11. useCallback does not automatically make an application faster.
12. Measure performance before adding unnecessary memoization.
57. One final way to understand it
Imagine you have a parent:
Parent
|
|-- count
|
|-- handleClick
|
↓
Child
Without useCallback:
Parent renders
↓
new handleClick
↓
Child receives new function
↓
Child may render again
With useCallback:
Parent renders
↓
dependencies unchanged
↓
same handleClick reference
↓
React.memo Child
↓
Child can skip rendering
So the simplest definition is:
useCallbackis used when you want React to keep the same function reference between renders until its dependencies change.
And the most important practical combination to remember is:
useCallback
+
React.memo
↓
stable function props
↓
fewer unnecessary child renders
That is the core idea behind useCallback.