benchpresser
benchpresser

Reputation: 2188

Javascript: Store a global variable for a single page application

A have a react application using a single page. I call index.html and use ajax(axio) and update the page. I do not use any routing.

I have some global variables and will use in the whole scope of the application. The variables are primitive type integer for example. Some of the variables may be updated during the app lifecycle and some remain constant. But I should be able to reach them from all react components/javascripts. They may contain business related constants or example decimal format mask, keeping them private in each component will not be useful.

There is no need/reason to store it on the disk (localStorage).

Question is: what is the best way (performance etc) storing the global variable foo in the app?

window.foo = 10 or
window.sessionStorage.foo = 10

AFAIK, window.foo is for a single page and sessionStorage allows using within multiple pages within the same origin. What is best in my case when I use a single page? Are there any other drawbacks of window.foo usage? Security is not important, the vales stored are not sensitive. Most critical is the performance.

Upvotes: 1

Views: 1577

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

You probably want to use context rather than either of those. From that documentation:

Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.

Definitely don't use global variables. The global namespace is incredibly crowded, and adding to it is generally not best practice. If you did use a global for this, I'd recommend using just one, and having it refer to an object with properties for the various pieces of information you want to share. Note that they'll be window-specific.

One reason to possibly consider using sessionStorage (or perhaps periodically synchronizing your React context to it) is if you want changes in one window to be reflected in another window. Two windows/tabs from the same origin share the same sessionStorage and can get an event (storage) when the other one changes that storage. So if the global information were an app theme (say, light vs. dark), changing it in one tab could also affect the other tab if you respond to the storage event by updating your React context. Note that sessionStorage (and localStorage) only store strings, so the usual thing is to convert to JSON when storing (JSON.stringify) and from JSON when loading (JSON.parse).

Upvotes: 3

Related Questions