usePrevious Hook

MediumReact Hooks20 min15 tests

Build a usePrevious(value) hook that returns the value from the previous render (undefined on the first render), then wire it into a small counter UI that shows both the current and previous count.

A classic React interview question: implement a custom usePrevious hook that, given a value, returns whatever that value was during the previous render. On the very first render there is no previous value, so it returns undefined.

The trick is understanding the order in which useRef and useEffect run. A ref holds a mutable value that survives across renders without triggering re-renders. During render you read the ref (the value from last time), and after render commits, an effect writes the current value into the ref so it's ready for next time.

In this exercise you'll implement usePrevious inside App.tsx and use it to drive a counter. The UI has:

  • An Increment button that bumps a count.
  • A live region (role="status") showing Current: N.
  • A second live region (role="status") showing the previous count: Previous: M once a previous value exists, and a placeholder (Previous: —) on the first render when there is none.

Each time you click Increment, "Current" should jump to the new number and "Previous" should show the number that was displayed just before the click.

Requirements

  • Implement a usePrevious(value) hook inside App.tsx using useRef + useEffect that returns the value from the previous render and undefined on the first render.
  • Render a heading for the counter (e.g. "Counter").
  • Render an Increment button (a real <button>) that increases the count by 1.
  • Show the current count in an element with role="status" as the text "Current: N".
  • Show the previous count in a separate element with role="status": "Previous: M" when a previous value exists, and "Previous: —" on the first render (no previous value).
  • Use only inline styles and import only from 'react'.
Hints (3)
  1. useRef gives you a mutable container that persists across renders but does NOT cause a re-render when you change .current — perfect for stashing the prior value.
  2. Read ref.current DURING render to get the previous value, then update ref.current = value inside a useEffect so it runs AFTER the render commits (next render will read the value you just stored).
  3. On the first render the ref starts as undefined, so usePrevious returns undefined — render a placeholder like "—" when previous is undefined rather than printing the word undefined.

Topics

  • React
  • React Hooks

Asked at

Myntra · Ola · Meesho · Paytm · CRED · Zomato

Join Us
blur