The example that I’m dealing with: I have an array that I’m mapping over. For each index of the array, one component is to be shown, and then after x time it’s replaced with a different component (permanently).
const Parent = ({ array }) => {
const [isVisible, setIsVisible] = useState(true);
setTimeout(() => {
setIsVisible(false);
}, 1000);
return array.map((item, index) => {
return (
<div key={index}>
{isVisible && <Child>{item}</Child>}
{!isVisible && <Child2>{item}</Child2>}
</div>
)
})
}
The above code works as intended at the first index. After the state change, following array items do not ‘switch’ components. Only the second component is rendered (because !isVisible is true).
Is there a way to have a state variable for each index of this dynamic array?
2
Answers
You should perform your setTimeout inside a useEffect, otherwise it’ll run every render.
To answer your question though, yes you could put this in its own component to simplify the logistics of it. This lets each element manage its own timer instead of the parent managing all its children. This only works for simple cases. If you wanted something more complex, for example, each child is visible one second after the last one, the parent would need to do some management via forwardProps or props or broadcast events.
You can extract the logic into a separate component.
Working example: