Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

setting state in nested setTimeouts bug

I’m trying to add JSX elements to a state array on a timer. So once the component is rendered, after 1200ms, a JSX element should be added to the array. 2 Seconds later, another JSX element should be added to the array.

The issue is, once the second setBlocks is called, the first JSX Element gets removed. Wondering if there is a way around this, or a better way to pull this off. Here is the useEffect:

  useEffect(() => {
    setTimeout(() => {
      setBlocks([...blocks, serverBlock]);
      setTimeout(() => {
        setBlocks([...blocks, commandBlock]);
      }, 2000);
    }, 1200);
  }, []);

And here is how I’m rendering the elements:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{blocks.map((block) => block)}

>Solution :

You should pass an updater function to setBlocks so you can change the state based on the actual previous value.

You also need to return a cleanup function from useEffect to cancel the timeout when the component is unmounted.

useEffect(() => {
    const id = setTimeout(() => {
      setBlocks(prevBlocks => [...prevBlocks, serverBlock]);
      setTimeout(() => {
        setBlocks(prevBlocks => [...prevBlocks, commandBlock]);
      }, 2000);
    }, 1200);
    return () => clearTimeout(id);
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading