search

Home  >  Q&A  >  body text

Why does useEffect ignore the last element of the array?

<p>I am learning React, especially learning useEffect. </p> <p>What I can't figure out is why useEffect skips the last element of the array. </p> <p>Can someone kindly explain why and how to fix it? </p> <pre class="brush:php;toolbar:false;">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]]) }</pre> <p><br /></p>
P粉814160988P粉814160988472 days ago416

reply all(1)I'll reply

  • P粉553428780

    P粉5534287802023-08-15 00:58:02

    Your useEffect will not run because users[index] has the same value

    Change it to index

    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!');
      }, [index]) // 更改为 `[index]`
    
    }

    reply
    0
  • Cancelreply