MediumConcept

What is the difference between useMemo and useCallback in React?

Technology:
React
Experience:
Mid-level,
Senior

Quick answer

useMemo caches the result of a calculation, while useCallback caches a function definition; both only recompute when their dependencies change.

Detailed explanation

useMemo(() => compute(a, b), [a, b]) returns the cached value. useCallback(fn, deps) is shorthand for useMemo(() => fn, deps): it returns the same function instance between renders.

Neither makes your app faster by default; each adds its own cost. Use useMemo for genuinely expensive calculations, and use useCallback mainly when the function is passed to a child wrapped in React.memo or is a dependency of another hook. A stable function reference is useless if the child is not memoized, since the child re-renders with its parent anyway.

Example

jsx
const visible = useMemo(
  () => todos.filter(t => t.status === filter),
  [todos, filter]
);

const handleSelect = useCallback((id) => setSelected(id), []);

const Row = React.memo(function Row({ item, onSelect }) { /* ... */ });
<Row item={item} onSelect={handleSelect} />

Key points

  • useMemo returns a value, useCallback returns a function
  • Both depend on a dependency array
  • Measure before optimising; memoisation has a cost
  • ReactEasy

    What are React hooks and what are the rules of hooks?

    Hooks are functions such as useState and useEffect that let function components use state, lifecycle behaviour and other React features; they must be called at the top level of a component or custom hook, never inside loops, conditions or nested functions.

    Junior 路 Mid-level 路 React Hooks
  • ReactEasy

    Why do we need keys in React lists?

    Keys give each list item a stable identity so React can match items between renders and correctly add, remove or reorder them without recreating or mixing up their state.

    Junior 路 Mid-level 路 Performance
  • ReactMedium

    How does useEffect work in React and what is the dependency array?

    useEffect runs a function after the component renders; the dependency array tells React when to re-run it: with no array it runs after every render, with an empty array only after the first, and with values only when those values change.

    Junior 路 Mid-level 路 React Hooks
  • ReactMedium

    What is the difference between useRef and useState in React?

    Updating state triggers a re-render, while changing a ref's .current value does not; use state for data shown on screen and refs for DOM access or values that must persist without causing renders.

    Mid-level 路 Senior 路 React Hooks
  • ReactMedium

    What is the difference between SSR, SSG and CSR in React?

    CSR renders in the browser after JavaScript loads, SSR renders the HTML on the server for each request, and SSG renders the HTML once at build time; SSR and SSG give crawlers and users content faster, which helps SEO.

    Mid-level 路 Senior 路 Performance