I'm developing a react.js project and before the main component is rendered, I call a function that returns an object that all components should be able to access. What is the correct way of doing this in react? Currently, I'm just passing it as a prop to the main component and then I suppose I should have to remember to pass it as a prop to all other components. Is there an easier or better way of doing this?
-
Searching your title, I found this possible duplicate https://stackoverflow.com/questions/34351804/how-to-declare-a-global-variable-in-react – mplungjan Jan 09 '18 at 17:50
2 Answers
It seems like you are doing something like Redux. Passing the object as props should be okay. You could make a higher-order component that wraps your components and adds access to that global object via props. This is similar to Redux's connect
.

- 7,360
- 4
- 40
- 58
As the expectation in React is application-wide concerns ,like a flux/redux/apollo store, are kept in a root provider component’s context and then accessed elsewhere in the component tree via a Higher Order Component or render props. This provides relief from globals and circular dependencies, and makes testing those components easier.
However, if you have non-component code that will need access to configuration values, you may need to use config
global and writing components in a way that accepts config values from props.

- 2,974
- 2
- 8
- 15
-
Would it be simpler to just have an exports file or something similar with all the things I want to have available globally or is this bad practice? – ninesalt Jan 09 '18 at 22:21
-
Sensitive values (session secrets, database passwords, etc.) and server-only concerns should continue to be loaded via secured environment variables (better using node-config as Since node-config is a server-side module it reads files only). – toufek khoury Jan 11 '18 at 09:22