Boolean State for Toggles
What you'll learn: How to use useState with true/false values to control toggleable UI elements like visibility, modals, and switches.
The Core Idea
One of the most common patterns in React is showing/hiding something or toggling between two states: on/off, open/closed, visible/hidden. Boolean state is perfect for this because you only have two options—exactly what true and false represent.
The Pattern
When you need a toggle, initialize useState with a boolean:
const [isOpen, setIsOpen] = useState(false);
Then flip it with the setter, often in response to a click:
<button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
The ! operator flips the boolean: if isOpen is true, !isOpen becomes false, and vice versa.
Common Use Cases
Show/Hide Content:
const [isVisible, setIsVisible] = useState(false);
return (
<>
<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? 'Hide' : 'Show'}
</button>
{isVisible && <p>Now you see me!</p>}
</>
);
Open/Close Modals:
const [isModalOpen, setIsModalOpen] = useState(false);
On/Off Switches:
const [isEnabled, setIsEnabled] = useState(false);
Naming Convention
Prefix boolean state with is, has, or should to make it obvious you're working with true/false:
isOpen/setIsOpenhasError/setHasErrorshouldShowDetails/setShouldShowDetails
Key Takeaway: Boolean state with useState(true/false) is the go-to pattern for any two-option toggle—use descriptive names and the ! operator to flip between states cleanly.