React Foundations · Performance

Memoising a function

useCallback

Memoising a function with useCallback

Every render builds new function objects. That is usually harmless — until you pass one to a memoised child. A fresh reference each render tells the child its props changed, so the memoisation you paid for does nothing.

useCallback keeps the same function between renders, and rebuilds it only when a dependency changes:

const increment = useCallback(() => {
  setCount((current) => current + 1);
}, []);

The dependency array works like useMemo's. List the values the function reads; when one changes, React makes a new function. An empty array means the function is created once and reused for the life of the component.

With the React Compiler, this is usually handled for you: it memoises the functions a component creates, so a handler no longer changes identity on every render by default. useCallback therefore becomes an escape hatch — reach for it when you need to pin a function's identity on purpose, such as a value you put in an Effect's dependency array.

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps) — the same idea applied to a function.

Your job is to memoise an event handler.

Challenge

A click handler is rebuilt on every render, and it should be stable. Export an App component from App.jsx that keeps a count in state and renders a button labelled Count: 0, with its click handler wrapped in useCallback.

The Test clicks the button once and expects the label to read Count: 1. The starter never changes the count, so the Test fails.

App.jsx
export function App() {
  return <button>Count: 0</button>;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.