UseCallback a powerful hook in React.


Why useCallback?
React’s useCallback
hook improves the performance of components in the application by re-rendering them only when a specific value changes. It enhances the optimization of the application by doing so.
First let understand what this rendering or re-rendering means.
In web applications, rendering
refers to the process of displaying content (such as HTML, CSS, and JavaScript) on the screen for the user. Rendering occurs whenever the application needs to update the user interface (UI) based on state, data, or user interaction.
Rendering the same content more than once is called re-rendering
.
How does useCallback works?
Basically, works in two different ways.
- In this method there are two functions the first one or the parent one creates a function using
useCallback
. The parent component's initial rendering is the only time the function is constructed. It is then supplied as a prop to the child component.
import React, { useCallback } from 'react';
function ParentComponent() {
// Memorize the function to avoid re-creation on every render
const onButtonClick = useCallback(() => {
console.log("Child button clicked!");
}, []); // Empty array ensures the function reference stays constant
return (
<div>
<h1>Parent Component</h1>
<ChildComponent onButtonClick={onButtonClick} />
</div>
);
}
function ChildComponent({ onButtonClick }) {
console.log("Child component rendered");
return (
<button onClick={onButtonClick}>
Press Me
</button>
);
}
export default ParentComponent;
Here, in the code above, the onButtonClick
function is created only once when the parent function is initialized, and then it is passed to the child function as a prop. This way, even if the parent function re-renders, the onButtonClick
method won’t be regenerated.
- By passing the dependency as a property into the callback function.
import { useCallback } from 'react';
function clickHandling({ props }) {
const onButtonClick = useCallback(() => {
console.log('Button clicked!');
}, [props]);
return (
<button onClick={onButtonClick}>
Click me!
</button>
);
}
In the code above, the useCallback
hook is being used to create a onButtonClick
function that will only be recreated if the props
prop changes.
Conclusion.
useCallback is the most common and useful hook in React. Thank you for reading this article. I hope it has been helpful.
#React
Subscribe to my newsletter
Read articles from PRASHANT MISHRA directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
