The useCallback
hook is a React hook that lets you optimize the performance of your function components by caching the functions that don't change between renders. This is especially useful for functions that are passed as props to child components, because it prevents the child components from re-rendering every time unless its props have changed.
Here is an example of how to use the useCallback
hook:
Copy codeimport React, { useState, useCallback } from 'react';
function Example() {
// Declare a state variable and a function to update the state
const [count, setCount] = useState(0);
// Declare a function that will be passed as a prop to a child component
const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<ChildComponent onClick={handleClick} />
</div>
);
}
function ChildComponent(props) {
return (
<button onClick={props.onClick}>
Click me
</button>
);
}
In this example, the handleClick
the function is wrapped with useCallback
, and the count
variable is passed as the second argument to useCallback
. This means that the handleClick
function will only be re-created if the count
variable changes. This prevents the child component from re-rendering every time the parent component re-renders, and improves the performance of the app.