'Interval inside useEffect with unwanted multi execution of the return function
I am using useEffect in React to add and remove uuids to an array (which then are getting rendered as "special effects"). Problem is when I look in the console, '1' is being written and then '2' 2x or 3x times (and then '1' again and so on). I know I have 'bubbles' in the useEffect dependency array so the return function is being executed. So is this the right way I am using the setInterval here and is the multiple showing '2' in the console unwanted behavior (I know it is not a bug) of the local development server (npm start => react-scripts start)?
Thanks for any advice!
const config: configType = { drinks: [{ drinkUuid: 'uuid1', drinkname: 'name1' }, { drinkUuid: 'uuid2', drinkname: 'name2' }], templates: ['stuff1', 'stuff2']};
const [bubbles, setBubbles] = useState<bubblesType>(config.drinks.map(({ drinkUuid }) => ({ drinkUuid, bubbles: [] })));
useEffect(() => {
// normally for every witth 'forEach', but in this example only for the first 'config.drinks'
const drinkUuid = config.drinks[0].drinkUuid
const match = bubbles.findIndex(e => e.drinkUuid === drinkUuid)
const interval1 = setInterval(() => {
console.log('1')
const offsetTimout = Math.round(randomNum(0,2000))
setTimeout(() => { // do after random Timeout
// Create uuid
const bubbleUuid = uuidv4()
// add bubble uuid to array
setBubbles(e => Object.assign([...e], {
[match]: {
...e[match],
bubbles: [...e[match].bubbles, bubbleUuid]
}
}))
setTimeout(() => {
// remove bubble uuid from array after timeout
setBubbles(e => Object.assign([...e], {
[match]: {
...e[match],
bubbles: [...e[match].bubbles.filter(e => e.bubbleUuid !== bubbleUuid)]
}}))
}, 5000)
}, offsetTimout)
}, 1000);
return () => {
console.log('2')
clearInterval(interval1)
};
}, [bubbles]);
function randomNum(min: number, max: number) {
return Math.random() * (max - min + 1) + min
}
type configType = {
drinks: {
drinkUuid: string,
drinkname: string,
}[],
templates: string[],
}
type bubblesType = {
drinkUuid: string,
bubbles: string[],
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
