Hi i am creating a project but not sure how to use the useEffect, the toggle button will toggle between green and red and the same time there is a counter will keep track the number of toggle is pressed and also is there a way to use toggle without using the boolean. thanks
function App() {
const [isToggled, setToggled] = useState(true);
const [counterState, setCounterState] = useState(0);
const toggleGreenRed = () => setToggled(isToggled ? 'Green' : 'Red' );
const incrementCounter = () => setCounterState(counterState 1);
useEffect(() => {});
return (
<div>
<button onClick={toggleGreenRed}>Toggle status</button>
<h1>{isToggled}</h1>
<h3>{counterState}</h3>
</div>
);
};
CodePudding user response:
There is a simple way of doing it, without using a useEffect hook
.
Here, you can see the example without using useEffect
hook.
import { useState, useEffect } from "react";
const App = () => {
const [isToggled, setToggled] = useState(true);
const [counterState, setCounterState] = useState(0);
const toggleGreenRed = () => {
setToggled(!isToggled);
setCounterState(counterState 1);
};
return (
<div>
<button onClick={toggleGreenRed}>Toggle status</button>
<h1>{isToggled ? "Green" : "Red"}</h1>
<h3>{counterState}</h3>
</div>
);
};
In here, what I've done so far is: increase the counter on the same time, whenever you press the button.
But if you wants to try with useEffect
here is the code:
import { useState, useEffect } from "react";
const App = () => {
const [isToggled, setToggled] = useState(true);
const [counterState, setCounterState] = useState(-1);
const toggleGreenRed = () => setToggled(!isToggled);
useEffect(() => {
setCounterState(counterState 1);
}, [isToggled]);
return (
<div>
<button onClick={toggleGreenRed}>Toggle status</button>
<h1>{isToggled ? "Green" : "Red"}</h1>
<h3>{counterState}</h3>
</div>
);
};
In here, you can see, useEffect
has isToggled
dependency. Which means, whenever the isToggled
value change, the useEffect
run and increase the value of counter.
You can learn more about useEffect
hook from react official doc.