React - what is the proper way to do global state?

I have here an app, and I want the App component to hold the current logged in user. I have the following routes and components.

Basically, every component in my app will make use of the user object. Sure I can pass the user as props to each and every component, but that is not elegant. What is the proper React way of sharing the user prop globally?

const App = () => { const [user, setUser] = useState(null); return ( <Router> <div className="app"> <Topbar /> <Switch> <Route path="/login" exact component={Login} /> <Route path="/home" exact component={Home} /> <Route path="/" exact component={ShopMenu} /> <Route path="/orders"> <Orders /> </Route> <Route path="/wishlist" exact component={Wishlist} /> <Route path="/wallet" exact component={Wallet} /> <Route path="/cart" exact component={Cart} /> </Switch> <BottomBar /> </div> </Router> ); }; 
1

2 Answers

Take a look at React Context and more specifically useContext as you're using hooks.

The idea of context is exactly that - for you to be able to share updateable state to the descendants without having to pass it from component to component.

const UserContext = React.createContext(null); const App = () => { const [user, setUser] = useState(null); return ( <Router> <div className="app"> <UserContext.Provider value={user}> <Topbar /> <Switch> <Route path="/login" exact component={Login} /> <Route path="/home" exact component={Home} /> <Route path="/" exact component={ShopMenu} /> <Route path="/orders"> <Orders /> </Route> <Route path="/wishlist" exact component={Wishlist} /> <Route path="/wallet" exact component={Wallet} /> <Route path="/cart" exact component={Cart} /> </Switch> <BottomBar /> </UserContext.Provider> </div> </Router> ); }; 

Then, in your component:

const Topbar = () => { const user = useContext(UserContext); // use `user` here }; 

If you want to have access to the setter (setUser) you can pass it through the context as well.

2

Welcome to stack overflow;

Yes you can save your state globally for which react-redux library react offers in which you need to store your state globally and you can access state in any component from redux

here is the complete guide

You can also check

complete guide here of how to use redux with react

Also you can use context api check here for context api

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like