1

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.

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.

Here is a snippet of my global state

import React from "react";

const GlobalState = React.createContext(null);

const socket = 'http://localhost:5000/';

const fetch_all_users = () => {
    fetch(socket + 'get_users_data')
        .then(response => response.json())
        .then(json => {
            console.log(json)
        })
        .catch(error => {
            console.log(error);
        });
}

const fetch_all_doors = () => {
    fetch(socket + 'get_doors_data')
        .then(response => response.json())
        .then(json => {
            console.log(json)
        })
        .catch(error => {
            console.log(error);
        });
}
2
  • If you are passing props to just first (or maybe second) child, I will not use context, otherwise if more child of childs need this info, would use context, but it's just my approach. Commented Nov 18, 2019 at 16:32
  • I think, first of all, you need to read a bit about context, and how it is used! What is provider, what is consumer, how to extract that said globalState. What have you done so far ? Commented Nov 18, 2019 at 16:49

2 Answers 2

8

You can actually use context as a global state but note that while you are fetching your data, the initial data of context might be null, so you can show a loading screen.

also you can use the useEffectHook but i will rather go for a complete component as the context provider.

also note that you will not be able to trigger an update on context. so if you need to update the state at a latter state, you might need to somehow reload the whole app or use redux or any state management of your choice

Sign up to request clarification or add additional context in comments.

3 Comments

This is more comment, not an answer!
Unfortunately i can't add comment to the question just yet
;) some contributions for you
0

react-query is a neat library to manage data that is retrieved from the backend.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.