Back to React Hooks
6

useCallback

Memoize functions to prevent unnecessary child re-renders

Advanced

Core Concepts

  • useCallback returns a memoized version of a function
  • The function only changes when dependencies change
  • Used with React.memo to prevent child re-renders
  • Similar to useMemo, but for functions instead of values

Live Demo

Test it: Type in the input below and watch the console. The "bad"button logs on every keystroke, the "good" one stays silent.

Rendered Without useCallback

Re-renders on every keystroke

Rendered With useCallback

Skips unnecessary re-renders

Open DevTools console to see which buttons re-render

useMemo vs useCallback

useMemo

// Memoizes the RESULT
const value = useMemo(() => {
  return expensiveCalculation(a, b);
}, [a, b]);

useCallback

// Memoizes the FUNCTION
const fn = useCallback(() => {
  doSomething(a, b);
}, [a, b]);

When to Use useCallback

Good use cases

  • • Passing callbacks to memoized children
  • • Functions in useEffect dependencies
  • • Event handlers for list items

Bad use cases

  • • Every function (premature optimisation)
  • • Components not wrapped in memo
  • • Simple components that render fast