skip to Main Content

I came accross this code

  const [count, setCount] = useState(0);
  useEffect(() => {
    const timerId = setTimeout(() => setCount(count + 1), 1000);
    return () => setTimeout(timerId);
  });

I know useEffect syntax as

useEffect(() => {
    something...which is executed
  });

but in the code i see its returning inside useEffect

useEffect(() => {
    ....
    return () => 
  });

As per my understanding how its different from just

  useEffect(() => {
    //const timerId = setTimeout(() => setCount(count + 1), 1000);
    setTimeout(() => setCount(count + 1), 1000);
    //return () => setTimeout(timerId);
  });

i am bit confused how this works

2

Answers


  1. As pointed out in the answer here the return of the useEffect is to clean up and, the returned function is run when the component is unmounted or every time it is rendered.

    So to answer how is

    useEffect(() => {
        const timerId = setTimeout(() => setCount(count + 1), 1000);
        return () => setTimeout(timerId);
    });
    

    different from

    useEffect(() => {
        //const timerId = setTimeout(() => setCount(count + 1), 1000);
        setTimeout(() => setCount(count + 1), 1000);
        //return () => setTimeout(timerId);
    });
    

    I think it is the confusion on the part of the Author of the first snippet. I think the intended code was

    useEffect(() => {
        const timerId = setTimeout(() => setCount(count + 1), 1000);
        return () => clearTimeout(timerId);
    });
    

    Since the timeout is bound to the window(global scope), the author meant to clear the previous timeout on each render or when the component is unmounted.

    Login or Signup to reply.
  2. If you return function inside useEffect, it’s called cleanup function This function is executed when the component is unmounted.

    What the author was trying to do is that clear the timer when the component is unmounted but, I think the code you came across kinda confusing anyway

    I think it should be like this..

      const [count, setCount] = useState(0);
      useEffect(() => {
        const timerId = setTimeout(() => setCount((count) => count + 1), 1000);
        return () => clearTimeout(timerId);
      }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search