Sobes.tech
Middle+

Tell about useCallback — use case, why is it needed?

sobes.tech AI

Answer from AI

useCallback is a React hook that returns a memoized version of a function that only changes if its dependencies change. It is used for performance optimization to avoid creating a new function on every render, which is especially important when passing functions to child components that depend on prop comparison.

Usage scenario:

If you have a component that accepts a callback function as a prop, and this component is optimized with React.memo, then without useCallback, the child component will re-render every time because the function is recreated.

Example:

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

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

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

  const increment = useCallback(() => {
    setCount(c => c + 1);
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <Button onClick={increment}>Increment</Button>
    </div>
  );
}

Here, useCallback prevents the creation of a new increment function on each render, which helps prevent unnecessary re-renders of the Button component.

Tell about useCallback — use case, why is it needed… - sobes.tech