Redux – avoid to pass props down component tree manually – 2. Use Provider to make store accessible to all components

This way every component in the tree can access the store directly. So you don’t need to pass the store manually any more

This solution is actually based on React’s Contenxt.

function render(){
		
    ReactDOM.render(
    	<Provider store = {rootStore}>	
    		<AppComponent appName="React Demo Site"/>
    	</Provider>,
    	
        document.getElementById('root'));
}


class AppComponent extends Component {
  render() {
    return (

      <div className="App">
	  	...
        <CounterComponent/>
        ...
      </div>
    );
  }
}


class CounterComponent extends Component {
    constructor(props){
        super(props);
    }

    render(){
        return (

            <div>
                <h2>Counter</h2>
                <h3>{this.context.store.getState().counter.value}</h3>
                <div>
                    <button onClick={ e =>  this.context.store.dispatch({type: 'counterChange', amount:  1}) }> + </button>
                    <button onClick={ e =>  this.context.store.dispatch({type: 'counterChange', amount: -1}) }> - </button>
                </div>
            </div>
        );
    }

}

//You need this only if a component needs to retrieve data from the context
CounterComponent.contextTypes = { 
	store: PropTypes.object
}; 


But it still sucks in that the CounterComponent is coupled with the root store structure.

  • Not good in terms of ecapsulation.
  • The CounterComponent is not really reuable, if another app with another store structure wants to contain it

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.