Easy

useToggle

Prompt

Create a custom hook useToggle that manages a boolean state with a toggle function. It should accept an optional initialValue (default false) and return an array with the current value and a toggle function.

This hook is useful for show/hide modals, expand/collapse sections, on/off switches, and any other true/false UI state.

Playground

Hint 1

One piece of state (useState), one function that flips it. The toggle function should use the updater form: setState(prev => !prev).

Hint 2

Return an array [state, toggle] so the consumer can name them whatever fits their context, like [isOpen, toggleOpen] or [showMenu, toggleMenu].

Solution

Explanation

This might be the simplest custom hook you'll ever write, but don't underestimate it. Interviewers ask it because it's a clean test of whether you understand useState, useCallback, and how to design a reusable hook API.

export const useToggle = (initialValue = false) => {
const [state, setState] = useState(Boolean(initialValue));

const toggle = useCallback(() => {
setState((prev) => !prev);
}, []);

return [state, toggle];
};

Let's walk through the decisions here:

We wrap initialValue in Boolean() as a safety measure. If someone accidentally passes 0 or '' or null, Boolean() converts it to false cleanly instead of storing a non-boolean value.

The toggle function uses the updater form prev => !prev to flip the state. !true gives false, !false gives true. Simple. We wrap it in useCallback with an empty dependency array so the function is created once and stays the same forever. This is safe because the updater form doesn't rely on any outside variable.

We return an array [state, toggle] instead of an object. Why? Same reason useState returns an array: it lets the consumer name things whatever they want. One component can write const [isOpen, toggleOpen] = useToggle(), another can write const [showMenu, toggleMenu] = useToggle(). With an object, you'd be stuck with fixed names.

In practice, you'll use this hook all the time. Show/hide a modal, expand/collapse a section, toggle dark mode, open/close a sidebar. Any boolean flip. Without this hook, you'd write the same three lines (useState + flip function) in every component. That's the whole point of custom hooks: take repeated patterns and give them a name.