Skip to main content

how to use useCallback hook in react with example

ยท 2 min read
Parth Maheta

The useCallback hook is another useful React hook that is used to memoize a callback function, similar to useMemo. It's particularly handy when you want to prevent unnecessary renders of child components that rely on functions passed as props.

Here's a basic explanation of how to use the useCallback hook:

import React, { useState, useCallback } from 'react';

const ChildComponent = ({ onClick }) => {
console.log('ChildComponent rendered');
return <button onClick={onClick}>Click me</button>;
};

const ParentComponent = () => {
const [count, setCount] = useState(0);

// Using useCallback to memoize the click handler function
const handleClick = useCallback(() => {
console.log('Button clicked');
setCount(prevCount => prevCount + 1);
}, []); // An empty dependency array means the function won't change over time

return (
<div>
<p>Count: {count}</p>
<ChildComponent onClick={handleClick} />
</div>
);
};

const App = () => {
return <ParentComponent />;
};

export default App;

In this example:

  1. We have a ChildComponent that takes an onClick prop.

  2. The ParentComponent has a state variable count and a callback function handleClick that increments the count when the button is clicked.

  3. The useCallback hook is used to memoize the handleClick function. By providing an empty dependency array ([]), we indicate that the function does not depend on any variables from the component's scope and won't change over time.

  4. The ChildComponent renders a button that triggers the onClick callback passed as a prop.

  5. When you click the button, the handleClick function is called, and the count is incremented. The ChildComponent only re-renders if its props change, and thanks to useCallback, the callback function is memoized and won't change between renders.

This can be especially useful when passing callbacks to child components. By memoizing the callback with useCallback, you ensure that the child component doesn't unnecessarily re-render when the parent component renders. It's an optimization to consider when dealing with performance concerns in your React applications.