React useCallback Guide: Optimize Performance

The useCallback hook in React is used to optimize performance by caching a function to ensure that a new function instance is not created when a component is re-rendered.

The useCallback function takes two parameters: a callback function and a dependency array. The callback function will only be recreated when any dependencies in the array change. If the dependency array is empty, the callback function will only be created once during the initial rendering of the component.

Scenarios for using useCallback include:

  1. Pass the callback function to the child component to prevent unnecessary re-rendering of the child component.
  2. Passing the callback function as a dependency of the effect ensures that the effect is only executed when specific dependencies change.
  3. When optimizing components with memo, pass the callback function as the second argument to memo, to ensure that the component will only re-render when the callback function changes.

Sample code:

import React, { useCallback } from 'react';

const MyComponent = () => {
  const handleClick = useCallback(() => {
    console.log('Button clicked');
  }, []);

  return (
    <button onClick={handleClick}>Click me</button>
  );
};

In the example above, the handleClick function is only created once during the initial rendering of the component and will not create a new instance when the component re-renders.

bannerAds