javascript / beginner
Snippet
Managing Boolean State with useState
The useState hook allows you to add state to functional components. In this example, we use a boolean value to track whether a button is 'on' or 'off'.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
import React, { useState } from 'react';function ToggleButton() {const [isOn, setIsOn] = useState(false);return (<button onClick={() => setIsOn(!isOn)}>{isOn ? 'ON' : 'OFF'}</button>);}
react
Breakdown
1
const [isOn, setIsOn] = useState(false);
Initializes a state variable 'isOn' with 'false' and a function 'setIsOn' to update it.
2
onClick={() => setIsOn(!isOn)}
An event handler that flips the current boolean value using the logical NOT operator (!).