Accepted answer

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.


i don't know what they're trying to say with this "react context" stuff - they're talking greek, to me, but here's how i did it:

carrying values between functions, on the same page

in your constructor, bind your setter:

this.setsomevariable = this.setsomevariable.bind(this);

then declare a function just below your constructor:

setsomevariable(propertytexttoadd) {
        myproperty: propertytexttoadd

when you want to set it, call this.setsomevariable("some value");

(you might even be able to get away with this.state.myproperty = "some value";)

when you want to get it, call var myprop = this.state.myproperty;

using alert(myprop); should give you some value .

extra scaffolding method to carry values across pages/components

you can assign a model to this (technically this.stores), so you can then reference it with this.state:

import reflux from 'reflux'
import actions from '~/actions/actions'

class yourform extends
        this.state = {
            someglobalvariable: '',
        this.listenables = actions;
        this.basestate = {
            someglobalvariable: '',

    onupdatefields(name, value) {
            [name]: value,

    onresetfields() {
           someglobalvariable: '',
const reqformdata = new yourform

export default reqformdata

save this to a folder called stores as yourform.jsx.

then you can do this in another page:

import react from 'react'
import reflux from 'reflux'
import {form} from 'reactstrap'
import yourform from '~/stores/yourform.jsx'


class somepage extends reflux.component {
    constructor(props) {
        this.state = {
            somelocalvariable: '',
        this.stores = [
    render() {

        const myvar = this.state.someglobalvariable;
        return (
export default somepage

if you had set this.state.someglobalvariable in another component using a function like:

setsomevariable(propertytexttoadd) {
       myglobalvariable: propertytexttoadd

that you bind in the constructor with:

this.setsomevariable = this.setsomevariable.bind(this);

the value in propertytexttoadd would be displayed in somepage using the code shown above.


globalthis may be supported in some browsers.
you can refer following links


for only declaring something, try this. make sure myobj is assigned at the proper time for you want to access it in render(), many ways was published before this thread. maybe one of the simplest ways if undefined then create it does the job.

declare global {
  interface window {
    myobj: any;


create a file :

import react from "react";

const appcontext = {};

export default appcontext;

then in app.js, update the value
import appcontext from './appcontext';

appcontext.username = uname.value;

now if you want the username to be used in another screen:

import appcontext from './appcontext';

appcontext.username to be used for accessing it.


maybe it's using a sledge-hammer to crack a nut, but using environment variables (with dotenv you can also provide values throughout your react app. and that without any overhead code where they are used.

i came here because i found that some of the variables defined in my env files where static throughout the different envs, so i searched for a way to move them out of the env files. but honestly i don't like any of the alternatives i found here. i don't want to set up and use a context everytime i need those values.

i am not experienced when it comes to environments, so please, if there is a downside to this approach, let me know.


the best way i have found so far is to use react context but to isolate it inside a high order provider component.


can keep global variables in webpack i.e. in webpack.config.js

externals: {
  'config': json.stringify({ global_variable: "global var value" })

in js module can read like

var config = require('config')
var global_variable = config.global_variable

hope this will help.


here is a modern approach, using globalthis, we took for our react native app.

globalthis is now included in...


// define our parent property accessible via globalthis. also apply the typescript type.
var app: globalappvariables;

// define the child properties and their types. 
type globalappvariables = {
  messagelimit: number;
  // more can go here. 

// set the values. = {
  messagelimit: 10,
  // more can go here.

// freeze so these can only be defined in this file.

app.tsx (our main entry point file)

import './appglobals'

// other code


const chatgroupquery = usequery(get_chat_group_with_messages_by_id, {
  variables: {
    messagelimit:, // 👈 used here.


create a file named "config.js" in ./src folder with this content:

module.exports = global.config = {
    i18n: {
        welcome: {
            en: "welcome",
            fa: "خوش آمدید"
        // rest of your translation object
    // other global config variables you wish

in your main file "index.js" put this line:

import './config';

everywhere you need your object use this:



is not recommended but.... you can use componentwillmount from your app class to add your global variables trough it... a bit like so:

componentwillmount: function () {
    window.myvars = {
        ajax: require('../helpers/ajax.jsx'),
        utils: require('../helpers/utils.jsx')

still consider this a hack... but it will get your job done

btw componentwillmount executes once before rendering, see more here:


beyond react

you might not be aware that an import is global already. if you export an object (singleton) it is then globally accessible as an import statement and it can also be modified globally.

if you want to initialize something globally but ensure its only modified once, you can use this singleton approach that initially has modifiable properties but then you can use object.freeze after its first use to ensure its immutable in your init scenario.

const myinitobject = {}
export default myinitobject

then in your init method referencing it:

import myinitobject from './myinitobject'
myinitobject.someprop = 'i am about to get cold'

the myinitobject will still be global as it can be referenced anywhere as an import but will remain frozen and throw if anyone attempts to modify it.

example of react state using singleton (see usercontext.tsx)

if using react-create-app

(what i was looking for actually) in this scenario you can also initialize global objects cleanly when referencing environment variables.

creating a .env file at the root of your project with prefixed react_app_ variables inside does quite nicely. you can reference within your js and jsx process.env.react_app_some_var as you need and it's immutable by design.

this avoids having to set window.myvar = %react_app_my_var% in html.

see more useful details about this from facebook directly:

Related Query

More Query from same tag