prabha pattabiraman
prabha pattabiraman

Reputation: 223

How to store user profile information and access it globally in react components

I am using a passport for authenticating the user. After successful authentication, I would like to show the username and id in one of the react components for now. There could be more places where I need to access user information in the future.

How should I accessing user profile information in independent react components?

I tried storing the user information in a cookie. Accessing the cookie in every component seems to be messy.

app.post('/login/callback', auth.authenticate('saml', { failureRedirect: '/', failureFlash: true }), function (req, res) {
// stores the cookie information
    res.cookie('cookie1', req.user.id, { secure: true, signed: true, expires: new Date(Date.now() + 3600) });
    res.redirect('/');
   }
);

I would like to access the user principal globally across all the react components.

Upvotes: 10

Views: 17935

Answers (1)

thuva4
thuva4

Reputation: 1225

There are multiple options for Global State management.

  1. Local Storage: Use the Browser local storage to save details
  2. Session Storage: This is similar to Local Storage with just one difference: that is while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends.
  3. Context: Context is designed to share data that can be considered “global” for a tree of React components
  4. Redux: Use State management library to manage the state in one place.

Upvotes: 12

Related Questions