Read here. Code on desktop. The coding workspace opens on screens 1024px and wider.
JavaScript interview question
useToggle
easy10 min
Manage a boolean React state with one stable utility that flips it or sets an explicit value.
Requirements
Implement useToggle(initialValue = false), returning [value, toggle]. The state is a boolean.
Calling toggle() or toggle(undefined) flips the current value. toggle(true) and toggle(false) explicitly set the value. Other argument types are outside the contract.
Keep toggle reference identity stable across rerenders and state changes. Previously captured toggles must use current state.
Multiple flips in a single batch must each apply. The initial argument initializes state only on mount; changing it later does not reset state.
Mounted instances are independent. This is a real React hook, not a mutable standalone state helper.
Examples
Example 1
Input: const [value, toggle] = useToggle(); toggle();
Output: false initially; true on the next render.
Example 2
Input: toggle(false);
Output: The next rendered value is false.
A tuple containing the boolean and a toggle/set utility.
What the tests check
Defaults to false
Accepts initial true without resetting on rerender
Flips in both directions
Supports explicit true and false
Undefined requests a flip
Applies multiple batched flips
Preserves mixed operation order in a batch
Keeps the utility stable across renders and changes