Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Toggle a boolean value in the state of a React component – the right way

Let's say you have a button that will just toggle a boolean in the state of a React component:

export const MyButtonComponent = (props) => {
    const [foo, setFoo] = useState(false);
    const handleClick = () => { /* to be added */};
    return (
        <button onClick={handleClick}>Toggle</button>

Initially for me, the most intuitive way to do it seemed to be:

const handleClick = () => setFoo(!foo);

However, it seems that this may lead to some corner-case (and very annoying) bugs. If you need to set a state variable based on its previous value, it is recommended to use a function param in the useState hook:

const handleClick = () => setFoo((foo) => !foo);

Note that this will apply also if we want to do operations as incrementing or decrementing, given that they also set a state variable based on its previous value:

const incrementingOnClick = () => setFoo((foo) => foo + 1);
Home Screencasts Best of Newsletter Search X