Object state hook with shallow merges that skip no-op updates
A search page keeps its filters in one object: { query, page, sort, inStock }. With plain useState, every update needs setFilters((prev) => ({ ...prev, page: 1 })), it is easy to forget the spread, and setting a field to the value it already has still creates a new object (so memoized children and effects run again for nothing). Implement a React hook, useMergeState, that holds an object and updates it with shallow merges.
function useMergeState<T extends object>(
initial: T | (() => T),
): [
state: T,
merge: (patch: Partial<T> | null | undefined | ((prev: T) => Partial<T> | null | undefined)) => void,
reset: () => void,
]
initial is the starting object. If it is a function, call it once, on the first render, and use its return value.merge(patch) shallow-merges patch into the state: keys in the patch overwrite the same keys in the state, and all other keys stay. Nested objects are replaced, not deep-merged.merge also accepts an updater function. It receives the latest state and returns a patch. Several merge calls in the same event all apply, in order.undefined is removed from the state (the key no longer exists on the object).Object.is, so a new array with the same items is a change),{}, null or undefined,undefined is not in the state.reset() restores the initial state from the first render.merge and reset keep the same identity across renders.const [filters, merge, reset] = useMergeState({ query: 'shoes', page: 3, sort: 'price' });
merge({ page: 1 });
// { query: 'shoes', page: 1, sort: 'price' }
merge((prev) => ({ page: prev.page + 1 }));
// { query: 'shoes', page: 2, sort: 'price' }
merge({ sort: undefined, inStock: true });
// { query: 'shoes', page: 2, inStock: true } ('sort' is gone)
merge({ query: 'shoes' });
// nothing changed: filters is the same object as before
reset();
// { query: 'shoes', page: 3, sort: 'price' }
merge and reset happen inside ReactDOM.flushSync.===), not only equal.Object.assign(window, { useMergeState }); below “Do not edit below this line”. The tests use it to call your hook.