React · Senior · Question 17 of 75

What does this hook do?

const useHandler = (f) => {
  const ref = useRef(f);
  ref.current = f;
  return useCallback((...args) => ref.current(...args), []);
};

Explanation

The callback reference is stable (handy for memo children and effect dependencies), but inside it always sees fresh props and state. Caveat: writing ref.current during render formally breaks render purity; React offers useEffectEvent for this task, and inside effects you'd update the ref in useLayoutEffect.

Further reading

Problem with a question

React · Senior · question 17

Test yourself

Take the React · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz