title: Why change State inside setTimeout make an infinity loop
body: <p>I have a <strong>functional component</strong> and I want to change State inside a <code>setTimeout</code>, but I don't know why it causes the component to be in an infinite loop!<br></p>
  <blockquote>
  <p>Here is my <strong>Functional Component</strong>:</p>
  </blockquote>
  <pre><code>import { useState } from &quot;react&quot;;
  
  function Card() {
    const [booksState, setBooks] = useState({
      books: [
        { name: &quot;Harry&quot;, id: 1 },
        { name: &quot;Potter&quot;, id: 2 },
        { name: &quot;John&quot;, id: 3 },
      ],
    });
  
    console.log(&quot;test&quot;);
  
    setTimeout(() =&gt; {
      let newBooks = [
        { name: &quot;test1&quot;, id: 4 },
        { name: &quot;test2&quot;, id: 5 },
        { name: &quot;test3&quot;, id: 6 },
      ];
  
      setBooks({
        books: [...booksState.books, ...newBooks],
      });
    }, 2000);
  
    return &lt;div&gt;TEST&lt;/div&gt;;
  }
  
  export default Card;
  
  </code></pre>
  <blockquote>
  <p>The <strong>console log</strong>:</p>
  </blockquote>
  <p><a href="https://i.stack.imgur.com/UyxRD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UyxRD.png" alt="enter image description here" /></a></p>