I'm learning the useEffect; I'm running into an exercise with a non-empty independency array since I'm passing the index of the array.
The problem is that I get same name repeated.
This is my code and below is the result.
let users = ['Oliver', 'Thomas', 'George', 'George', 'William']
export default function App() {
const [index, setIndex] = useState(0);
console.log('RENDER');
useEffect(() => {
console.log('Hello ' + users[index]);
console.log('Side Effect RUNS!');
setTimeout(() => setIndex(index => index + 1), 1000)
if (index === users.length - 1) {
return
}
}, [index])
}
RESULT:
RENDER
Hello Oliver
Side Effect RUNS!
RENDER
Hello Thomas
Side Effect RUNS!
RENDER
Hello George
Side Effect RUNS!
RENDER
Hello George
Side Effect RUNS!
RENDER
Hello William
Side Effect RUNS!
RENDER
Hello undefined
Side Effect RUNS!
RENDER
Hello undefined
Side Effect RUNS!
RENDER
Hello undefined
Side Effect RUNS!
Also as you can see, I get undefined.
How can I solve the problem?