In my React app, I need to store some data which needs to be accessible pretty much everywhere, but don't want to keep it in a global (i.e., static) data structure so that it's easy to mock for my unit tests and the style guide.
The data I mean is for example:
- a constant
IN_BROWSERthat istruein browser builds andfalsein Node. - a constant
IS_MOBILEthat is initialized on the startup in the browser - data of the user who is currently logged in,
- url of the API that I connect to (which is localhost, staging server, or production, depending on the config)
Right now I have a file called sessionData.js that stores this data, and whenever I need, I do require('./sessionData') in my code and use it. I can mock it for my unit tests using rewire and, as they run sequentially, it works fine for now. It is problematic for the styleguide, because there each example can show the view from the perspective of a different user (so ideally each example would have its own sessionData).
IN_BROWSER is currently a global, which also turns out to be a bad idea, because it puts an implicit dependency on the initialization code from every module.
I see that I could pass my sessionData and other stuff via props to every component down the hierarchy, but this seems like a lot of redundancy.
Is there any design pattern to solve it better?
