
what is useCallback() ?
useCallback() is a React Hook used to memoize functions, so they are not re-created on every re-render unless necessary.
Why Use useCallback()?
In React, functions are recreated every time a component renders.
This can cause problems like:
- Unnecessary re-renders in child components
- Loss of performance with heavy operations
đź”§ useCallback() solves this by caching the function until its dependencies change.
Syntax
const memoizedFn = useCallback(() => {
// your function logic
}, [dependencies]);
- memoizedFn: returns the same function instance unless dependencies change.
- dependencies: array of values the function depends on.
Example Without useCallback() (causes extra re-renders)
function Parent() {
const [count, setCount] = useState(0);
const handleClick = () => {
console.log('Clicked');
};
return (
<>
<button onClick={() => setCount(count + 1)}>+1</button>
<Child onClick={handleClick} />
</>
);
}
const Child = React.memo(({ onClick }) => {
console.log('Child rendered');
return <button onClick={onClick}>Child Button</button>;
});
Every time Parent re-renders, handleClick is recreated → Child also re-renders.
Example With useCallback() (prevents extra re-render)
import React, { useState, useCallback } from 'react';
function Parent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log('Clicked');
}, []); // memoized function
return (
<>
<button onClick={() => setCount(count + 1)}>+1</button>
<Child onClick={handleClick} />
</>
);
}
const Child = React.memo(({ onClick }) => {
console.log('Child rendered');
return <button onClick={onClick}>Child Button</button>;
});
Now Child won’t re-render unless handleClick actually changes.
Summary
Feature | Description |
---|---|
useCallback() | Memoizes a function |
Prevents | Recreating the same function on every render |
Useful with | React.memo, performance-heavy functions |
Returns | A memoized version of the callback function |
Common Use Cases
- Passing callbacks to memoized child components
- Preventing re-renders in large component trees
- Performance optimization in lists, charts, or animations
Comments
Add new comment