Home > Net >  useEffect doesn't trigger at all
useEffect doesn't trigger at all

Time:11-11

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:

  1. No dependency passed:
useEffect(() => {
  //Runs on every render
});
  1. An empty array:
useEffect(() => {
  //Runs only on the first render
}, []);
  1. 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

  • Related