a78d43a0cd7059a7a66b
Β·4 min read

useCallback and useMemo in React

react
hooks
useMemo
useCallback
performance
4d5fd787ac74e0caa4f7

Sohan R. Emon

Developer, Learner, Tech Enthusiast

These are two important hooks that help optimize your components by memoizing values and functions. Let's dive into the key differences between them and how to use them effectively.

What is useCallback?

useCallback is a React hook that returns a memoized callback function. It's primarily used for optimizing functions that depend on props or state. The key points to remember about useCallback are:

  • Returns a memoized callback: This means it returns a function that won't change unless one of its dependencies has changed. It's perfect for preventing unnecessary re-renders when passing callbacks to child components.

  • Output of the callback is callable: The function you pass into useCallback is not automatically called. You need to invoke it when you want it to run.

  • Dependencies control when the callback changes: You provide an array of dependencies to useCallback, and the callback will only be recreated if one of these dependencies changes.

How to use useCallback

Here's an example of how to use useCallback:

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

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

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

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

In this example, the handleClick function is wrapped with useCallback. It depends on the count state, so we include [count] as the dependency array. This ensures that handleClick is memoized and only recreated when count changes.

What is useMemo?

On the other hand, useMemo is a hook that returns a memoized value. It's used for optimizing values that depend on props or state. Here are the key points about useMemo:

  • Returns a memoized value: It caches the result of an expensive computation so that it doesn't recompute on every render.

  • Output of useMemo is not callable: Unlike useCallback, you can't invoke the value returned by useMemo as a function. It's just a cached value.

  • Dependencies control when the value changes: Similar to useCallback, you specify an array of dependencies, and the value will only recalculate if one of these dependencies changes.

How to use useMemo

Here's an example of how to use useMemo:

jsx
import React, { useState, useMemo } from 'react';

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

  const expensiveCalculation = useMemo(() => {
    // Do some expensive calculation here
    return count * 2;
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <p>Expensive calculation: {expensiveCalculation}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

In this example, expensiveCalculation is memoized using useMemo. It depends on the count state, so we include [count] in the dependency array. This ensures that the expensive calculation is only performed when count changes.

key differences between useCallback and useMemo:

FeatureuseCallbackuseMemo
PurposeMemoizes a callback functionMemoizes a computed value
OutputReturns a memoized callbackReturns a memoized value
InvocationCallback function must be called manuallyValue is accessed directly
DependenciesRecreates callback when any dependency changesRecalculates value when any dependency changes
Use CaseOptimizing functions that depend on props or stateOptimizing values that depend on props or state

Remember that choosing between useCallback and useMemo depends on whether you want to memoize a function or a value and how they relate to your component's props or state.

Summary

In a nutshell, useCallback is for memoizing functions, and useMemo is for memoizing values. Both of these hooks are essential for optimizing the performance of your React components by controlling when functions are recreated or values are recalculated.

Found this useful?