Sometimes, we want to toggle a boolean state in a React component.
In this article, we’ll look at how to toggle a boolean state in a React component.
Toggle a Boolean State in a React Component
To toggle a boolean state in a React component, we can pass in a function that takes the existing value of the state and returns the next state into a state setter function.
For instance, we write:
import React, { useState } from "react";
export default function App() {
const [check, setCheck] = useState(false);
return (
<>
<div>
<button onClick={() => setCheck((prevCheck) => !prevCheck)}>
{check.toString()}
</button>
</div>
</>
);
}
We call the useState
hook to create the check
state.
Then we pass in a function that calls setCheck
with a callback that takes the prevCheck
parameter, which has the current value of the check
state, as the value of the onClick
prop.
And we return the new value of the check
state as the return value.
Therefore, when we click the button, we see check
toggle between true
and false
.
Conclusion
To toggle a boolean state in a React component, we can pass in a function that takes the existing value of the state and returns the next state into a state setter function.