← All tasksReact · Junior
useToggle hook
Write a useToggle(initial = false) hook. It returns an array [value, toggle]: the current boolean value and a function that flips it.
The toggle function must stay the same between renders, so it can be passed to memoized components and effect dependencies without side effects.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (4)
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()); const first = result.current[1]; act(() => result.current[1]()); expect(result.current[1]).toBe(first);