useState hook with a reset that reruns the initializer
An expense form starts with one empty line item that has a fresh id and today’s date. After the user submits, the form should go back to that starting state, but with a new line item: a new id, the date of the moment it was reset, and not the same object as before. Implement a React hook, useResettableState, that works like useState and adds a reset function.
function useResettableState<T>(
initialValue: T | (() => T),
): [
state: T,
setState: (next: T | ((previous: T) => T)) => void,
reset: () => void,
]
state and setState behave like useState: setState accepts a value or an updater function, and an initializer function is called once on mount, not on every render.reset() sets the state back to its initial value:
initialValue is a function, call it again and use its result. Every reset therefore produces a fresh value.initialValue itself.reset() uses the initialValue from the latest render. Changing initialValue does not change the current state; it only affects the next reset().setState and reset calls in the same event apply in the order they were made.setState and reset keep the same identity across renders.const newItem = () => ({ id: crypto.randomUUID(), date: new Date().toISOString(), amount: 0 });
function ExpenseForm() {
const [item, setItem, reset] = useResettableState(newItem);
// item = { id: 'a1', date: '2026-03-02T09:00:00Z', amount: 0 }
setItem((it) => ({ ...it, amount: 42 }));
// item = { id: 'a1', ..., amount: 42 }
reset();
// item = { id: 'b7', date: '2026-03-02T09:05:00Z', amount: 0 } (newItem ran again)
}
const [page, setPage, resetPage] = useResettableState(1);
// In one click handler:
setPage((p) => p + 1); resetPage(); setPage((p) => p + 1);
// page === 2
setState and reset happen inside ReactDOM.flushSync. Some tests count how many times the component rendered and how many times the initializer was called.Object.assign(window, { useResettableState }); below “Do not edit below this line”. The tests use it to call your hook.