Skip to main content
TOPIC 5 OF 6 · 2 MIN READ

useCallback and useMemo

`useCallback` and `useMemo` are React hooks used for performance optimization. `useCallback` memoizes functions to prevent unnecessary re-creations, while `useMemo` memoizes computed values to avoid expensive recalculations.

Key concepts

useCallback

A React hook that memoizes a function. Ensures the function reference remains stable between renders unless its dependencies change. Used to prevent unnecessary re-creations of functions and optimize child components that rely on function props.

useMemo

A React hook that memoizes a computed value, ensuring it is only recalculated when its dependencies change. Used to optimize performance by avoiding expensive calculations on every render.

Step by step

When to Use useCallback:

  • When passing functions as props to child components.
  • When the function depends on state or props that rarely change.

When to Use useMemo:

  • For optimizing expensive calculations that depend on specific variables.
  • When the computed value is used in the render but rarely changes.

Examples

useCallback Example:

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

function Counter() {
  const [count, setCount] = useState(0);
  const [incrementAmount, setIncrementAmount] = useState(1);

  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + incrementAmount);
  }, [incrementAmount]); // Recreates only when incrementAmount changes

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <input
        type="number"
        value={incrementAmount}
        onChange={(e) => setIncrementAmount(Number(e.target.value))}
      />
    </div>
  );
}

useMemo Example:

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

function ExpensiveComputationComponent() {
  const [count, setCount] = useState(0);
  const [multiplier, setMultiplier] = useState(1);

  const expensiveComputation = useMemo(() => {
    console.log('Computing...');
    return count * multiplier;
  }, [count, multiplier]); // Recomputes only when count or multiplier changes

  return (
    <div>
      <p>Computed Value: {expensiveComputation}</p>
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
      <input
        type="number"
        value={multiplier}
        onChange={(e) => setMultiplier(Number(e.target.value))}
      />
    </div>
  );
}

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus