Step 2.7: Connect Redux store to view (Demo)
Redux is currently the most popular Flux implementation, and the ecosystem of related libraries has grown as a result. This is one of the reasons why it is a very popular library within Microsoft products.
Various GitHub users have collected "awesome lists" of tech and articles related to Redux. Here is one such list, but it is literally impossible to list out all the related tech.
In this step, we introduce but one useful library that works with Redux: react-redux.
The official React Redux binding: react-redux
That's right, Redux doesn't only work with React. It can also be used with Vue.js, Angular, and React Native, to name a few.
<Provider> component
The store doesn't magically get passed to the views. It has to be supplied by a react-redux component called <Provider>. A <Provider> can be placed anywhere, but it's best to just make it available at the root the app:
const store = createStore(reducers);
const App = () => {
return (
<Provider store={store}>
<div>Hello World!</div>
</Provider>
);
};
connect() higher-order function
react-redux provides a connect() function that turns the Redux store and dispatch functions into props for React components. The state and action dispatchers are passed along with a <Provider> component.
const OldComponent = props => {
return <div>{props.foo}</div>;
};
const NewComponent = connect(
mapStateToProps,
mapDispatchToProps,
mergeProps,
options
)(OldComponent);
connect() takes in a few functions that map portions of the state tree and dispatcher functions into props. It is a higher-order function, meaning that the return value of connect() is a function that decorates OldComponent into a NewComponent with all the mapped props.
A mapStateToProps function selects out portions of the state tree. This function informs the connected view when to re-render based on a shallow comparison from previous state.
function mapStateToProps(state) {
return {
foo: state.foo
};
}
An optional mapDispatchToProps function will trigger the action message dispatch mechanism of Redux. It looks like this:
function mapDispatchToProps(dispatch) {
return {
// the dispatched message COULD be generated by an
// action creator instead
addTodo: () => dispatch({ type: 'addTodo', ... })
}
}