function Painter({tempArr}) {
const [arr, setArr] = useState([]);
useEffect(() => {
tempArr.map((item, index) => {
setTimeout(() => {
setArr([...arr, item]);
}, 2000 * index)
})
}, [tempArr])
I checked the state arr
has only one element in the array.
I expected arr
state will have all the elements of tempArr
array after the last timeout. But there is only new element in every re-rendering.
I found using the updater function solves the issue.
function Painter({tempArr}) {
const [arr, setArr] = useState([]);
useEffect(() => {
tempArr.map((item), index => {
setTimeout(() => {
setArr(prev => [...prev, item]); // using the updater function
}, 2000 * index)
})
}, [tempArr])
But I don't know why this one works but not the above one.