简体   繁体   中英

How to share a variable across components in ReactJS?

I am new to ReactJS and I want to share one variable between multiple components.

These components do not have a parent-child or any other kind of relationship.

class App extends React.Component {

   test() {
      if (globalVariable) { // I want this variable to be set in another component
          // Do something ...
      }
   }

   render() {
       // ...
   }
}

I am setting globalVariable in another component like this:

class Test extends React.Component {

   componentDidMount() {
      // Making an API call and setting globalVariable here.
   }

   render() {
       // ...
   }
}

How can I share the variable between multiple components? What is the best approach? I don't want to use Redux.

You can use Reacts built in context api.

https://reactjs.org/docs/context.html

When to Use Context

Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.

when you are building larger application go with Redux for global state management and another thing when ever you reload the page global state back to initial it is persistent so try to use local or session storage along with global state

you can read about Redux offical doc here https://react-redux.js.org/

in React there is one data binding: (So there is possibility pass state only from parent to child)

You can just pass state from parent to child

在此处输入图片说明


For global variables like language , theme etc. There is Redux or Context - if U don't want Redux/Mobx to avoid complicated architecture - then context is good idea.

Context allow You pass the state from >1 level depth in react tree.

在此处输入图片说明

There is defining the scopes by React.Providers eg.

  <ThemeContext.Provider value="dark">
    <Toolbar />
  </ThemeContext.Provider>

For getting the state from child component there is useContext hook

Well, if you are new in React you have to know differents concepts.

Experiment : This isnt an efficient solution but you can create an Patter component, in this patter component your gonna call define your two components and using a Prop. eg

Class PatterComponent extends React.Component {
render(){
  return{
    <>
     <App globalVariable="value"/>
     <Test globalVariable="value"/>
    </>
  }
}

}

Render this component like your principal component. And use the prop in test like this.props.globalVariable, your gonna have "value" as a result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM