Write useToggle(initial), the default export of useToggle.js. It returns a pair, [on, toggle]: on starts as initial, or false when there's no initial.
toggle() flips on. toggle(true) and toggle(false) set it. Anything else, like the click event React passes when you write onClick={toggle}, flips it too.
toggle is the same function on every render, so components can pass it to memoized children or list it in an effect's dependencies without causing extra work.
function Lamp() {
const [on, toggle] = useToggle();
return <button onClick={toggle}>{on ? "On" : "Off"}</button>;
}
The Preview shows Demo.jsx, a small lamp that uses your hook.
const { result } = renderHook(() => useToggle());
expect(result.current).toHaveLength(2);
expect(typeof result.current[1]).toBe("function");
const { result } = renderHook(() => useToggle());
expect(result.current[0]).toBe(false);
const { result } = renderHook(() => useToggle(true));
expect(result.current[0]).toBe(true);
const { result } = renderHook(() => useToggle());
act(() => result.current[1]());
expect(result.current[0]).toBe(true);
act(() => result.current[1]());
expect(result.current[0]).toBe(false);
const { result } = renderHook(() => useToggle());
act(() => result.current[1](true));
act(() => result.current[1](true));
expect(result.current[0]).toBe(true);
act(() => result.current[1](false));
expect(result.current[0]).toBe(false);
function Lamp() {
const [on, toggle] = useToggle();
return <button onClick={toggle}>{on ? "On" : "Off"}</button>;
}
render(<Lamp />);
await user.click(screen.getByRole("button"));
expect(screen.getByRole("button")).toHaveTextContent("On");
await user.click(screen.getByRole("button"));
expect(screen.getByRole("button")).toHaveTextContent("Off");
const { result, rerender } = renderHook(() => useToggle());
const first = result.current[1];
act(() => first());
rerender();
expect(result.current[1]).toBe(first);
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with useToggle. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.