Boolean state hook with stable enable, disable, toggle helpers
Modals, dropdowns, “show password” switches and loading indicators all need a single boolean, plus a few named ways to change it. Writing () => setOpen(true) inline creates a new function on every render, which defeats React.memo children and re-runs effects that depend on it. Implement a React hook, useFlag, that manages a boolean and exposes helpers that never change identity.
function useFlag(initial?: boolean | (() => boolean)): {
value: boolean;
enable: () => void;
disable: () => void;
toggle: () => void;
set: (next: boolean) => void;
}
initial defaults to false. If it is a function, call it once on the first render and use its result. Never call it again.enable() sets value to true, disable() sets it to false, and set(next) sets it to next.toggle() flips the latest value. Calling it several times in the same event applies every flip in order: two toggles leave the value unchanged, three flip it once.enable, disable, toggle and set keep the same identity for the lifetime of the component, including after value changes.function ShippingForm() {
const giftWrap = useFlag();
const details = useFlag(() => localStorage.getItem('showDetails') === 'yes');
return (
<>
<label>
<input type="checkbox" checked={giftWrap.value} onChange={(e) => giftWrap.set(e.target.checked)} />
Gift wrap
</label>
<button onClick={details.toggle}>{details.value ? 'Hide' : 'Show'} details</button>
<MemoizedHelpPanel onClose={details.disable} /> {/* never re-renders because of onClose */}
</>
);
}
const flag = useFlag(true);
flag.toggle(); // value === false
flag.toggle(); flag.toggle(); // same event: value === false (flipped twice)
flag.enable(); // value === true
ReactDOM.flushSync, sometimes several in one call, then reads value and compares helper identities across renders.Object.assign(window, { useFlag }); below “Do not edit below this line”. The tests use it to call your hook.