How to declare a global variable in React?

sapy picture sapy · Dec 18, 2015 · Viewed 287.3k times · Source

I initialized i18n translation object once in a component ( 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 render() method.

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

Answer

Naisheel Verdhan picture Naisheel Verdhan · Dec 18, 2015

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.