Read here. Code on desktop. The coding workspace opens on screens 1024px and wider.
JavaScript interview question
usePrevious
easy15 min
Track the previous distinct committed value, retaining it when a component rerenders with the same value.
Requirements
Implement usePrevious(value), returning undefined on the first render. After value changes, return its preceding distinct committed value.
Repeated renders with the same value must preserve the previous distinct value, rather than replacing it with the current value. For A → B → B → C, return undefined → A → A → B.
Compare values with Object.is: repeated NaN is unchanged, 0 and -0 are distinct, and objects use reference identity. Preserve returned object and function identities without calling or copying them.
Update stored history after commit in an effect. Only committed values enter history; do not write to refs while rendering. Instances are independent and history remains correct during Strict Mode replay.
Do not set React state simply to update history or cause an extra render. TypeScript should preserve the input type and include undefined in the result.
Examples
Example 1
Input: usePrevious("A"); // then render with "B", "B", "C"
Output: undefined, "A", "A", "B"
Example 2
Input: usePrevious(0); // then render with false
Output: undefined, 0
The prior distinct value, not merely the value from the last render.