简体   繁体   中英

State Management in React at component level

In case you are using Redux to manage the global state, how do you manage exclusive component state that used only by this component and its children(act like container)?

Edit I am already using useState() . I am asking for a better approach because I ended up with a lot of useState statements.

Any Ideas?

I think the container with complicated state that you want to control the same with pure React when redux and other tool manage state not yet appear. In your case, the Container is a root Component (like App Component at index). It manage complicated state object and pass key value or some function to children.

Class Container extend Component {
   state = {
       // complicated state
   }

   render() {
       return (
          <Children1 key1={this.state.value1...} />
          <Children2 key1={this.state.value2...} />
          <Children3 key1={this.state.value3...} />
       )
   }
}

Or you can use Functional Component to manage state more flexible:

const Container = () => {
   const [state1, setState1] = useState({ // some key: value here });
   const [state2, setState2] = useState({ // some key: value here });
   const [state3, setState3] = useState({ // some key: value here });
   return (
      <Children1 keyObject={state1} keyValue={state1...} />
      <Children2 keyObject={state2} />
      <Children3 keyObject={state3} />
   )
}

Answer with your Edit : I think useState is better approach for your case. When you doing with client-side, you must control where variable used . The splitting of state will help you control them more flexible. If you have a lot of useState statements, you should thinking about reworked structure of Container and children Component.

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