title: React updating State from Firebase Server
body: <p>I have a firebase database, that has a collection called &quot;post&quot; and in post there 6 variables (displayName, userName, verified, text, image, avatar). The idea is, there will be multiple posts in the database.</p>
  <p>React Code:</p>
  <pre><code>  const [posts, setPosts] = useState([]);
      
      //Whenever the firebase database changes, it runs this method
      useEffect(() =&gt; {
          db.collection(&quot;posts&quot;).onSnapshot((snapshot) =&gt;
              //Loops through all the posts and adds the data into an array
            setPosts(snapshot.docs.map((doc) =&gt; doc.data()))
          );
        }, []);
  </code></pre>
  <p>In react, I have two state variables, posts and setPosts. I'm assuming they are initially just set to empty arrays.</p>
  <p>Now I have the <code>useEffect</code> function, that I am told runs whenever the database changes/updated. First question, how does the function know that the database updated? In other words, how does the <code>useEffect</code> function work?</p>
  <p>Secondly, I'm pretty sure in the end, the post variable becomes a list of all the post objects in the database. I'm not sure how that happened. I have attached the code that updates this state above, but I'm not too sure how it works. Can you please break it down and explain how it works? I'm also not sure what the setPosts state is used for.</p>
  <p>Please let me know!</p>