Boolean hook with a stable turnOn, turnOff, toggle, set object
A settings screen has a dozen on/off rows: Wi-Fi, Bluetooth, dark mode, notifications. Each row is a memoized component that receives the switch’s actions as props. If the hook returns a fresh object (or fresh functions) on every render, every row re-renders whenever anything on the screen changes, and every effect that lists those actions as dependencies runs again. Implement a React hook, useSwitch, that manages one boolean and returns its actions as a single object that never changes identity, so callers can pass it around as one stable prop.
function useSwitch(initial?: boolean | (() => boolean)): [
on: boolean,
controls: {
turnOn: () => void;
turnOff: () => void;
toggle: () => void;
set: (next: boolean | ((previous: boolean) => boolean)) => void;
},
]
controls object.initial defaults to false. If it is a function, call it once on the first render and use its result. Never call it again.turnOn() sets the value to true. turnOff() sets it to false. toggle() flips the latest value.set(next) accepts a boolean, or a function that receives the latest value and returns the next one (like the setter from useState).toggle() calls leave the value unchanged; turnOn() then toggle() ends as false.controls object itself, and each function on it, keep the same identity for the lifetime of the component, including after the value changes.useSwitch is independent. Two switches in the same component have separate values and separate controls objects.const SettingRow = React.memo(function SettingRow({ label, on, controls }) {
return (
<label>
<input type="checkbox" checked={on} onChange={(e) => controls.set(e.target.checked)} />
{label}
</label>
);
});
function Settings() {
const [wifi, wifiControls] = useSwitch(true);
const [darkMode, darkModeControls] = useSwitch(() => matchMedia('(prefers-color-scheme: dark)').matches);
// Toggling dark mode does not re-render the Wi-Fi row: its props are the same.
return (
<>
<SettingRow label="Wi-Fi" on={wifi} controls={wifiControls} />
<SettingRow label="Dark mode" on={darkMode} controls={darkModeControls} />
</>
);
}
const [on, controls] = useSwitch(); // on === false
controls.toggle(); // true
controls.set((previous) => !previous); // false
controls.turnOn(); controls.toggle(); // same event: false
ReactDOM.flushSync, sometimes several in one call, then reads the value and compares identities across renders.Object.assign(window, { useSwitch }); below “Do not edit below this line”. The tests use it to call your hook.