The not so secret life of Provider in Redux

July 07, 2018 0 Comments

The not so secret life of Provider in Redux

 

 



I have always asked myself what the <Provider> does and why it is a neccessity while using redux.

How does react-redux make it possible for me to access my store objects.

My inquisitive nature led me to the react redux codebase. I expected to find a large compilcated <Provider> component, but to my suprise that wasn't the case.

I have ommited some code for readability sake.

import React from "react"; 
import PropTypes from "prop-types"; class Provider extends React.Component { constructor(props, context) { super(props, context); this.store = props.store; } getChildContext() { return { store: this.store }; } render() { return this.props.children; }
}
Provider.childContextTypes = { store: PropTypes.object
}; export default Provider;

What is the Provider doing

Provider makes use react's context api. Context provides a way to pass data through the component tree without having to pass props down manually at every level.

The provider makes store accessible to its child components via the getChildContext method. Therefore its children can access the store with props.context.store.

const Child = ({props}) => { console.log(props.context.store) return <div>child</div> 
}

Now Child can have access to the store without us passing it down explicitly

<Provider store={store}> <Child/> 
</Provider>

Also note the childContextTypes that is defined on the provider class. This is needed so that react can know the shape of data we are sharing via the context.

This is how the react-redux connect function is able to get our store objects. Below is a simplified version of the connect.

 
function connect(mapStateToProps, mapDispatchToProps) { return function(Component) { class App extends React.Component { constructor(props, context) { super(props, context); this.store = context.store.getState(); } render() { return <Component {...this.store}/>
} } App.contextTypes = { store: PropTypes.object }; return App; };
}


Tag cloud