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);
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.