FrontendPro

58Implement usePrevious() without causing an additional render

mediumAbout 35 minutesCodingreacthooksrefs

Problem

Implement usePrevious(value). It returns the value from the previous render (undefined on the first render), without causing any extra render.

function Price({ amount }) {
  const previous = usePrevious(amount);
  const direction = previous === undefined ? "" : amount > previous ? "▲" : amount < previous ? "▼" : "";
  return <span>{amount} {direction}</span>;
}

Also implement usePreviousDistinct(value), which returns the last value that was different from the current one, so re-renders with the same value do not lose it.

Requirements

  • usePrevious returns undefined on the first render and the previous render's value afterwards.
  • Neither hook may trigger a re-render: no setState in an effect.
  • Only committed renders count: do not write refs during render in usePrevious.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Step-by-step

Storing the previous value with useState and updating it in an effect means every change causes a second render. A ref can hold a value across renders without triggering one.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever