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);
š Neural Networks from Scratch - Presale
I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!
š Neural Networks from Scratch - Presale
I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!