useToggle
- React course
- Intermediate
- Lesson 2/80
- 4 min
Learn to write a useToggle hook that manages a boolean state.
useToggle
useToggle is one of the most commonly written custom hooks. It returns a boolean state and a function that flips it. Ideal for dropdowns, modals, checkboxes.
The shape: const [on, setOn] = useState(false); const toggle = () => setOn(o => !o); return [on, toggle];. Returning an array lets the calling component pick names freely.
This pattern is a limited variant of useState: it only flips between two values (true/false). Used in multiple components, it's a big convenience.
Why return an array
Custom hooks usually return arrays, because you can name array elements freely: const [visible, toggleVisible] = useToggle();. With an object, names would be fixed.
Returning fewer or more values is also easy: return [count, increment, decrement, reset];. The component picks what it needs, ignoring the rest.
This flexibility puts custom hooks in the same style as React's own hooks (useState, useReducer). Consistency makes learning easier.
Practice Write useToggle
Complete the skeleton. Write a useToggle hook. Define on state with useState(false). The toggle function should be () => setOn(o => !o). Return the array [on, toggle]. Export the hook.
Starter code
import { useState } from "react";
// Write the useToggle hook hereSample solution
import { useState } from "react";
function useToggle() {
const [on, setOn] = useState(false);
const toggle = () => setOn((o) => !o);
return [on, toggle];
}
export default useToggle;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does useToggle return?
- Object
- Single value
- Array: [value, toggle] Correct answer
- Function
Explanation: useToggle returns an [value, toggle] array.
2 Toggle operation
The toggle function flips the value with ____.
The toggle function flips the value with ! o.
Explanation: Flipped with ! o.
3 Match the useToggle parts
| Term | Meaning |
|---|---|
useState(false) |
Initial |
toggle |
Flips |
return [on, toggle] |
Array |
! o |
Method |