Day 15: useCallback hook in react
Today is my 15th day of learning React js where I learned about the concept of useCallback hook in react, when it is used and when not to use it? Here's the summary of What I learned:
What is useCallback?
The useCallback hook is a performance optimization mechanism in React that helps prevent unnecessary re-renders of child components when their parent component re-renders. It achieves this by memoizing (caching) callback functions based on their dependencies. It preserves function across renders to prevent unnecessary re-renders. If the dependencies haven't changed, the same function reference is returned, avoiding the creation of a new function object on every render. It prevents infinite loops by maintaining function references.
When to Use useCallback:
Example:
import React, { useState, useCallback } from 'react';
function ParentComponent() {
const [count, setCount] = useState(0); const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]); // Only recreate handleClick when count changes return (
<div>
<p>Count: {count}</p>
<ChildComponent onClick={handleClick} />
</div>
);
}function ChildComponent({ onClick }) {
return (
<button onClick={onClick}>Increment</button>
);
}
In this example, handleClick is memoized using useCallback with the dependency [count]. This ensures that the child component only receives a new function reference when count changes, preventing unnecessary re-renders even if the parent component re-renders due to other state changes.
When Not to Use useCallback:
Recommended by LinkedIn
Example (where useCallback is not needed):
JavaScript
function MyComponent() {
const handleClick = () => {
console.log('Clicked!');
};
return (
<button onClick={handleClick}>Click me</button>
);
}
Here, handleClick is a simple function without dependencies and is only used within the same component. Using useCallback wouldn't provide any performance benefit in this case.
Additional Considerations:
By understanding the use cases and limitations of useCallback, you can effectively leverage it to optimize your React components and enhance their performance.