title: React Fetch data and save it in global state via context API
body: <p>Is it a good idea to create a global state using the react context api and fetch data and save it in the context object so the child components can access the data. Or it's better to fetch data in the root component and pass it to children via props. </p>
  
  <p>If the global state using context api better, how do I fetch data and save it in the global state because fetch function is async and I've been using React useEffect to work around it. </p>
  
  <p>Here is a snippet of my global state</p>
  
  <pre><code>import React from "react";
  
  const GlobalState = React.createContext(null);
  
  const socket = 'http://localhost:5000/';
  
  const fetch_all_users = () =&gt; {
      fetch(socket + 'get_users_data')
          .then(response =&gt; response.json())
          .then(json =&gt; {
              console.log(json)
          })
          .catch(error =&gt; {
              console.log(error);
          });
  }
  
  const fetch_all_doors = () =&gt; {
      fetch(socket + 'get_doors_data')
          .then(response =&gt; response.json())
          .then(json =&gt; {
              console.log(json)
          })
          .catch(error =&gt; {
              console.log(error);
          });
  }
  </code></pre>