SE_1991
SE_1991

Reputation: 675

What's the best solution for storing a users id?

What's the best method of storing a users ID in ReactJS, so that all components have access to it?

I've looked into Redux and Context, but they seem massively overkill for just storing an ID (or maybe I'm missing something?). I've also looked at storing the ID in the parent component (App), but page refreshes lose the id :(.

Upvotes: 1

Views: 4870

Answers (3)

XxXtraCookie
XxXtraCookie

Reputation: 327

Keeping such sensitive data as a user id in storage is a bad bad idea! You need to fetch this data every time the user hard-refreshes his/her browser. Do not use storage for such savings!

Upvotes: 1

Amir Molaei
Amir Molaei

Reputation: 3830

If you want your data to be available even after closing and reopening the browser, LocalStorage is the appropriate place to store it; Otherwise SessionStorage keeps your data as long as the browser is open.

Upvotes: 2

Mark
Mark

Reputation: 2071

Session storage would probably best suit your needs

The sessionStorage property allows you to access a session Storage object for the current origin. sessionStorage is similar to localStorage; the only difference is while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends.

https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

You can then set/get the ID when you need to

sessionStorage.setItem('userID', 'value');
const USER_ID = sessionStorage.getItem('userID');

However, to keep the ID even after a page close you would need to use localStorage

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

localStorage.setItem('userID', 'value');
const USER_ID = localStorage.getItem('userID');

Upvotes: 8

Related Questions