Custom Hooks — Beginner React challenge.
Return the value a prop or state had on the previous render. A staple utility hook — trivial to write, tricky to get exactly right.
Requirements
- Return undefined on the very first render.
- On every subsequent render, return the value from the previous render (not the previous DISTINCT value — if the same value is passed twice in a row, the previous render's value is still returned).
- Do not cause additional re-renders.
- Must be safe under React StrictMode (no duplicated or skipped updates from double-invoked effects in development).
- Export a pure helper `getDeltaClassName(current, previous)` that returns "delta-initial" when previous is undefined, "delta-up" when current > previous, "delta-down" when current < previous, and "delta-same" when they're equal — used by consumers to style the displayed delta with CSS.
Signature
function usePrevious<T>(value: T): T | undefined
function getDeltaClassName(current: number, previous: number | undefined): string
Example
const prev = usePrevious(count);
// count: 0 → prev: undefined
// count: 1 → prev: 0
getDeltaClassName(5, 3); // "delta-up"
Constraints
- No external state.
- Must be safe under React strict mode.