useCallback Hook

The useCallback hook in React is used to memoize callback functions. It returns a memoized version of the callback that only changes if one of the dependencies has changed. This is useful to optimize performance, particularly when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

Basic Usage


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

export default function ExampleComponent() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []); // Empty array means the callback never changes

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={increment}>Click me</button>
    </div>
  );
}

When to Use useCallback

Prevent Re-creation of Functions: Use useCallback to prevent re-creation of functions on every render.

Optimized Child Components: Use useCallback when passing functions to memoized child components (React.memo) to prevent unnecessary re-renders.

Memoized Callback for Child Components


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

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

export default function ParentComponent() {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []); // Empty array means the callback never changes

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