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:
{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);
}, []);