DEV Community

Kudzai Murimi
Kudzai Murimi

Posted on

How does the useCallback hook differ from the useMemo hook?

useCallback and useMemo are both hooks in React that are used to optimize performance by memoizing values, but they differ in their use cases.

The useCallback hook is used to memoize functions. When you use useCallback, you create a memoized version of a function that is only recreated when one of its dependencies changes. This is useful when you want to pass a function as a prop to a child component, but don't want that child component to re-render every time the parent component re-renders. By memoizing the function, you can ensure that the child component only re-renders when necessary.

Here's an example of using useCallback to memoize a function:

const MyComponent = () => {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() => {
    setCount(count + 1);
  }, [count]);

  return (
    <button onClick={handleClick}>Clicked {count} times</button>
  );
};
Enter fullscreen mode Exit fullscreen mode

In the example above, the handleClick function is only recreated when the count state changes.

The useMemo hook, on the other hand, is used to memoize values that are expensive to compute. When you use useMemo, you create a memoized version of a value that is only recomputed when one of its dependencies changes. This is useful when you have a value that takes a long time to compute, and you don't want to recompute it every time the component re-renders.

Here's an example of using useMemo to memoize a value:

const MyComponent = () => {
  const [count, setCount] = useState(0);

  const expensiveValue = useMemo(() => {
    return computeExpensiveValue(count);
  }, [count]);

  return (
    <div>{expensiveValue}</div>
  );
};
Enter fullscreen mode Exit fullscreen mode

In the example above, the expensiveValue is only recomputed when the count state changes.

In summary, useCallback is used to memoize functions, while useMemo is used to memoize values.

Top comments (0)