javascript / beginner
Snippet
Toggling Boolean State Values in React Components
Boolean data types are essential in React for managing binary user interface states, such as visibility or active flags. By passing an updater function to the state setter, the component reliably flips the current boolean value to its opposite.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { useState } from 'react';function NotificationToggle() {const [isVisible, setIsVisible] = useState(true);const handleToggle = () => {setIsVisible((prev) => !prev);};return (<div><button onClick={handleToggle}>Toggle</button>{isVisible && <p>New message received!</p>}</div>);}
react
Breakdown
1
const [isVisible, setIsVisible] = useState(true);
Initializes a state variable holding a primitive boolean value of true.
2
setIsVisible((prev) => !prev);
Uses the logical NOT operator (!) inside a state updater callback to invert the boolean.
3
{isVisible && <p>New message received!</p>}
Evaluates the boolean value to conditionally display the message element.