Hook returning the last value that differed from the current
An order tracker wants to animate from the old status to the new one, for example “packed → shipped”. To do that, the component needs the status it showed before the current one. Re-renders caused by unrelated state, such as a ticking clock, must not wipe that out. Implement a React hook, useLastDistinct, that returns the most recent earlier value that was different from the current one.
function useLastDistinct<T>(value: T, isEqual?: (a: T, b: T) => boolean): T | undefined
undefined.Object.is by default, so NaN equals NaN. If you pass isEqual(a, b), use it instead. It may be a new inline function on every render.0, '', false) are values like any other.// Renders in order, with the value passed to useLastDistinct(status):
// render 1: 'packed' -> undefined
// render 2: 'packed' -> undefined (clock ticked, status unchanged)
// render 3: 'shipped' -> 'packed'
// render 4: 'shipped' -> 'packed' (still the last *different* value)
// render 5: 'delivered'-> 'shipped'
// Objects that are rebuilt on every render, compared by id:
const prevUser = useLastDistinct(user, (a, b) => a.id === b.id);
// { id: 1, name: 'Ada' } then { id: 1, name: 'Ada L.' } -> still undefined (same id)
// then { id: 2, name: 'Lin' } -> { id: 1, name: 'Ada L.' }
ReactDOM.flushSync, then reads what your hook returned in the latest render.Object.assign(window, { useLastDistinct }); below “Do not edit below this line”. The tests use it to call your hook.