Write a useToggle hook with a stable toggle function
Write useToggle(initial). It returns [on, toggle, setOn]: on starts as initial, or false when there's no initial. toggle() flips on, and setOn(value) sets it, like a state setter.
toggle must be the same function on every render, so it can go to a memo child or into an Effect's dependencies without causing extra work. It takes no arguments and ignores any it gets, so onClick={toggle} works. Calling it twice in one event flips on twice.
function Lamp() {
const [on, toggle, setOn] = useToggle();
return (
<>
<p>{on ? "On" : "Off"}</p>
<button onClick={toggle}>Toggle</button>
<button onClick={() => setOn(false)}>Turn off</button>
</>
);
}
import { useCallback, useState } from "react";
export function useToggle(initial = false) {
// Return [on, toggle, setOn], with a toggle that never changes.
}
- starts with the initial value, or false
- toggle flips the value each time
- setOn sets the value
- toggle is the same function after updates and renders
- two toggles in one event flip twice
- works as an onClick handler
- a memo child that gets toggle doesn't render again
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…