I’m just studying React and in particular I’m studying the useEffect.
What I’m failing to figure out is why the useEffect is skipping me the last element of the array.
Can someone kindly explain to me why and how to fix it please?
let users = ['Oliver', 'Thomas', 'George', 'William']
export default function App() {
const [index, setIndex] = useState(0);
console.log('RENDER');
useEffect(() => {
if (index === users.length - 1) {
return
}
setTimeout(() => setIndex(index => index + 1), 2000)
console.log('Hello ' + users[index]);
console.log('Side Effect RUNS!');
}, [users[index]])
}
3
Answers
The
if (index === users.length - 1)
statement literally skips the last element.You can simply make it
if (index >= users.length)
because you return before you it you should do
or you should
for the xisting code
This is because you made a condition to return in useEffect, if the index is equal to the last element index:
You need to make the if statement condition to return, if the index is greater than the last element index:
This will make the function work.
One last thing is that you need to clear the timeout to avoid memory leaks, and it may give you unexpected results sometimes.
Here is the full code: