useCallback in React

Expert-Level Explanation

useCallback is a hook that returns a memoized version of the callback function that only changes if one of its dependencies has changed. This is useful when passing callbacks to optimised child components that rely on reference equality to prevent unnecessary renders.

Creative Explanation

Think of useCallback as a memoization machine in a factory. This machine remembers the blueprint (the callback function) and only updates it when the raw materials (dependencies) change. If the raw materials are the same as last time, the machine reuses the existing blueprint instead of creating a new one.

Practical Explanation with Code

Example of using useCallback:

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

function MyComponent({ someProp }) {
  const [count, setCount] = useState(0);

  const memoizedCallback = useCallback(() => {
    // Function logic that uses `someProp`
  }, [someProp]);

  return <div onClick={memoizedCallback}>Count: {count}</div>;
}

In this example, memoizedCallback is only recreated if someProp changes.

Real-World Example

In a data grid component where rows can have action buttons, useCallback ensures that the action button's click handler is not recreated every time the grid re-renders, unless the data associated with that row (a dependency) changes.