useState that rejects invalid updates with an error message
Some state must never hold an invalid value: a cart quantity above the stock, a seat count of zero, a username with spaces. Instead of storing whatever the user typed and checking it everywhere it is read, the state itself can refuse bad updates and explain why. Implement a React hook, useValidatedState, that works like useState but runs every update through a validator first.
function useValidatedState<T>(
initialValue: T,
validate: (next: T, current: T) => string | null | undefined,
): [value: T, setValue: (next: T | ((current: T) => T)) => void, error: string | null]
validate returns an error message (a string) to reject the update, or null / undefined to accept it.
initialValue as is. It is not validated, and error starts as null.setValue(next) accepts a value or an updater function. An updater receives the latest accepted value.validate(next, current), where current is the latest accepted value.
error to that string.next and set error back to null.setValue calls in the same event apply in order. A rejected update does not stop the ones after it, and each updater sees the value left by the previous accepted update. error reflects the last call.validate is usually an inline function that reads props or state (for example the current stock). Always use the validate from the latest render.setValue keeps the same identity across renders, like the setter from useState.function QuantityPicker({ stock }) {
const [qty, setQty, error] = useValidatedState(1, (next) => {
if (!Number.isInteger(next)) return 'Enter a whole number';
if (next < 1) return 'At least 1';
if (next > stock) return `Only ${stock} left`;
return null;
});
return (
<>
<button onClick={() => setQty((q) => q - 1)}>-</button>
<span>{qty}</span>
<button onClick={() => setQty((q) => q + 1)}>+</button>
{error && <p role="alert">{error}</p>}
</>
);
}
// stock = 3, qty = 1
// "-" : 0 is rejected, qty stays 1, error 'At least 1'
// "+" : qty 2, error null
// "+" : qty 3
// "+" : 4 is rejected, qty stays 3, error 'Only 3 left'
// The validator also receives the current value:
const [handle, setHandle, error] = useValidatedState('ada', (next, current) =>
next === current ? 'That is already your handle' : null,
);
[value, setValue, error] array it returns. Updates are called inside ReactDOM.flushSync.Object.assign(window, { useValidatedState }); below “Do not edit below this line”. The tests use it to call your hook.