Sobes.tech
Junior — Middle

When is it recommended to use the useCallback hook in React components?

sobes.tech AI

Answer from AI

The useCallback hook in React is used for memoizing functions to prevent their re-creation on every component render.

It is recommended to use useCallback in the following cases:

  • When a function is passed to child components that are optimized with React.memo or shouldComponentUpdate, to prevent unnecessary re-renders.
  • When a function is used in dependencies of other hooks, such as useEffect or useMemo, and it is important for the function reference to remain stable.

Example:

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

function Parent() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount(c => c + 1);
  }, []); // function does not change on re-renders

  return <Child onClick={increment} />;
}

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

Without useCallback, the increment function would be recreated on every render, causing the Child component to re-render.

However, do not overuse useCallback, as memoization itself has overhead and is only beneficial for actual performance optimization.