how i can have the same effect on React? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

how i can have the same effect on React?

i want know if is posible obtain the same effect in other best way this is a link https://stackblitz.com/edit/react-ynmz6w?file=src%2Findex.js

2nd Nov 2020, 5:18 PM
Alessio Farroni
Alessio Farroni - avatar
1 Answer
+ 4
Yes. In the way below, you aren't gonna need useEffect. return ( <div> <h1>{first}</h1> <h1>{second}</h1> <button onClick={add}>Add</button> </div> ) This is just a setup, now we will create the "first" and "second" states and the "add" function. "second" state keeps increasing on each click, but "first" first checks that if the "second" state (the one that changes on every click), is it even or odd? If it is odd, we will add TWO to the "first" and ONE to "second", otherwise, just ONE to the "second" const [first, setFirst] = useState(0) const [second, setSecond] = useState(0) function add() { // check if it is odd if (second % 2 !== 0) { setFirst(first + 2) } // no else condition coz we wanna add ONE to second anyway. setSecond(second + 1) }
2nd Nov 2020, 5:48 PM
maf
maf - avatar