useState variant that returns a fallback for null or undefined
Settings screens often have values that are either chosen by the user or “not set”. A not-set value should display a sensible default instead of null. Implement a React hook, useFallbackState, that works like useState but returns a fallback value whenever the stored state is null or undefined.
function useFallbackState<T>(
fallback: T,
initialValue?: T | null,
): [T, (next: T | null | undefined | ((current: T) => T | null | undefined)) => void]
[value, setValue]. value is the stored state, or fallback when the stored state is null or undefined.null and undefined fall back. Other falsy values such as 0, '', false and NaN are real values and are returned as they are.initialValue is optional. When it is omitted, the stored state starts empty and the fallback is shown.setValue(next) stores next. Setting null or undefined resets the value to the fallback.setValue(fn) calls fn with the current displayed value, which is the fallback when the state is empty, and stores what it returns. Several updaters in the same event apply in order, like useState. Function arguments are always treated as updaters.fallback may change between renders. While the stored state is empty, return the latest fallback. Never copy the fallback into the stored state.setValue keeps the same identity across renders, so it is safe to use in effect dependencies and in memoized children.const [pageSize, setPageSize] = useFallbackState(25);
// pageSize === 25 (nothing stored yet)
setPageSize(50); // pageSize === 50
setPageSize(0); // pageSize === 0 (0 is a real value)
setPageSize(null); // pageSize === 25 (back to the fallback)
setPageSize((n) => n + 5); // the updater receives 25, so pageSize === 30
function Greeting({ defaultName }) {
const [name, setName] = useFallbackState(defaultName, null);
// defaultName 'Guest' -> name === 'Guest'
// defaultName 'Visitor' -> name === 'Visitor' (still nothing stored)
// setName('Ada') -> name === 'Ada', whatever defaultName is
}
ReactDOM.flushSync. The tests read the value your hook returns.Object.assign(window, { useFallbackState }); below “Do not edit below this line”. The tests use it to call your hook.