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>
);
}
import { useState } from "react";
export function usePrevious(value) {
// Return what value was before it last changed.
return undefined;
}
- 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
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…