For some reason I cannot trigger my useEffect. It is a simple counter of seconds. I added console.log just to check if it will ever trigger but it doesn't at all. The interesting part is that React prints out the counter as 1. So I thought that it gets in the useEffect once and that's it but it doesn't print anything in the console at all. Any solutions?
const LookForRanked = () => {
const [counter, setCounter] = useState(0);
useEffect(() => {
setCounter(counter 1);
console.log(counter);
}, 1000);
return (
<div className="time-searching">Searching: {counter} sec</div>}
)
}
export default LookForRanked;
CodePudding user response:
You are mistaking useEffect
for setTimeout
. useEffect
takes 2 parameters useEffect(<function>, <dependency>)
. And that <function>
runs every time there is a change in <dependency>
.
Some examples of dependency:
- No dependency passed:
useEffect(() => {
//Runs on every render
});
- An empty array:
useEffect(() => {
//Runs only on the first render
}, []);
- Props or state values:
useEffect(() => {
//Runs on the first render
//And any time any dependency value changes
}, [prop, state]);
CodePudding user response:
Solution
const LookForRanked = () => {
const [counter, setCounter] = useState(0);
useEffect(() => {
console.log(counter);
const interval = setInterval(() => {
setCounter(counter 1);
}, 1000);
return () => {
clearInterval(interval);
};
}, [counter]);
return (
<div className="time-searching">Searching: {counter} sec</div>}
)
}
export default LookForRanked
To create a counter in ReactJs, you need to use setInterval method to start the interval and there you need to provide the time in millisecond to update your counter state.
For more information - Counter Game in ReactJs