Sometimes, we want to toggle the boolean state of a React component.
In this article, we’ll look at how to toggle the boolean state of a React component.
How to toggle the boolean state of a React component?
To toggle the boolean state of a React component, we can call the state setter function with a function that returns the latest boolean value.
For instance, we write
const Comp = () => {
const [check, setCheck] = useState(false);
// ...
const toggle = () => {
setCheck((prevCheck) => !prevCheck);
};
//...
};
to create the check
state in the Comp
component.
Then we add the toggle
function that calls setCheck
with a function that returns the original value of the check
state, which is prevCheck
, negated to set check
to the negated value of prevCheck
.
Conclusion
To toggle the boolean state of a React component, we can call the state setter function with a function that returns the latest boolean value.
For instance, we write