useToggle

Easy

Prompt

Create a custom React hook called useToggle that manages a boolean state and toggles between true and false values.

This hook is useful when you need to show and hide modal, show more/show less text, open/close side menu.

Requirements

  • The hook should return an array with the following elements:
    • The current boolean state value
    • A function to toggle the state between true and false
  • The hook should accept an optional initialValue parameter (default to false)
  • The toggle function should simply invert the current state value (true → false, false → true)

Example

function ToggleComponent() {
const [isVisible, toggle] = useToggle(false);

return (
<div>
<p>
{isVisible
? 'Content is visible'
: 'Content is hidden'}
</p>
<button onClick={toggle}>Toggle Visibility</button>

{isVisible && (
<div>
This content will show and hide when toggled.
</div>
)}
</div>
);
}

Playground

Hint 1

Use the useState hook to create a state variable that will hold your boolean value.

const [state, setState] = useState(Boolean(initialValue));
Hint 2

The toggle function should be a simple callback that uses the functional form of the state setter to invert the previous state.

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

Solution

Explanation

The useToggle hook is a simple React hook that manages a boolean state with toggle functionality. Let's break down how it works:

const [state, setState] = useState(Boolean(initialValue));

First, we use the useState hook to create our state variable. We pass the initialValue to the Boolean() function to ensure we're working with a true boolean value, which handles cases where non-boolean values might be passed.

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

Next, we create a toggle function using useCallback. This function simply inverts the current state value by using the functional form of setState. The empty dependency array ensures our toggle function is only created once.

Using the functional form (prevState) => !prevState is important because it guarantees we're working with the most up-to-date state value, which is critical when state updates happen in quick succession.

return [state, toggle];

Finally, we return an array containing the state value and the toggle function. This follows the pattern of React's built-in hooks like useState, allowing the consumer to use array destructuring to name these values whatever makes sense in their context.

This hook makes toggling boolean state simple and reusable across your application. It's perfect for implementing common UI patterns like show/hide, expand/collapse, and on/off functionality.

00:00