Search code examples
reactjsjavascript-globalize

How to declare a global variable in React?


I initialized i18n translation object once in a component (a first component that loads in the app ). That same object is required In all other components. I don't want to re-initialize it in every component. What's the way around? Making it available to window scope doesn't help as I need to use it in the render() method.

Please suggest a generic solution for these problems and not i18n specific solution.


Solution

  • Why don't you try using Context?

    You can declare a global context variable in any of the parent components and this variable will be accessible across the component tree by this.context.varname. You only have to specify childContextTypes and getChildContext in the parent component and thereafter you can use/modify this from any component by just specifying contextTypes in the child component.

    However, please take a note of this as mentioned in docs:

    Just as global variables are best avoided when writing clear code, you should avoid using context in most cases. In particular, think twice before using it to "save typing" and using it instead of passing explicit props.