cf.completefrontend

Write the codeMedium

Write a usePrevious hook

Write usePrevious(value). It returns what value was before it last changed, so a component can show a price going from 4 to 5.

On the first render there's no earlier value, so it returns undefined. Renders that don't change value don't count: if the component renders again for another reason, usePrevious keeps returning the same earlier value. Compare values with Object.is, as React does.

function PriceTag({ price }) {
  const before = usePrevious(price);
  return (
    <p>
      Now {price}
      {before !== undefined && <span>, was {before}</span>}
    </p>
  );
}
Write this (usePrevious.js)
import { useState } from "react";
 
export function usePrevious(value) {
  // Return what value was before it last changed.
  return undefined;
}
The checks your code must pass
  • returns undefined on the first render
  • returns the old value after a change
  • follows each change
  • stays undefined until the value first changes
  • keeps the old value through renders that don't change it
  • compares objects by identity
  • in a component, an unrelated update keeps the old price

Try it in the editor

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…