Search code examples
reactjstypescriptglobal-state

React global state via props


Im using a shared global state as the following:

interface DashboardProps extends React.Props<Dashboard> {
    globalState? : GlobalState
}

export class Dashboard extends React.Component<DashboardProps, any>{

}

In AppLayout i call it:

<Route  path='/dashboard'>
   <Dashboard globalState={this.state} />
</Route>

let say that inside Dashboard class I need to change the globalState, whats the best way to do so?

Thanks


Solution

  • Props are readonly (see docs here). So, you either:

    1. implement globalstate as a state in your Dashboard component, then pass down the handler to children of Dashboard so that they can change globalState. For example:

    // dashboard component
    class Dashboard extends Component {
      constructor(props) {
        super(props);
        this.state = {
          globalState = /* some initial value */
        }
      }
    
      // handler to change globalState.
      globalStateHandler = (data) => {
        // perhaps some processing...
        this.setState({ 
          globalState: data,
        })
      }
      
      render() {
        return <ChildComponentOne>
          <ChildComponentTwo>
            <SomeComponentOne globalStateHandler={this.globalStateHandler}/>
            <SomeComponentOne globalStateHandler={this.globalStateHandler}/>
          </ChildComponentTwo>
        </ChildComponentOne>
      }
    
    }

    1. Use a state management library like redux, or flux. Using these libraries, you can keep the entire state of your apps and make them accessible in any of your components. This is probably the best option and many people have use these libraries to manage the state of their apps.

    2. You could store globalState in localStorage or window global variable. Probably not a good idea, but possible nonetheless.