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 just 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.
mapStateToProps
A mapStateToProps function returns portions of the state tree that will be passed to the component as props.
Under the hood, this function helps inform the connected view when it should re-render based on a shallow comparison with the previous state.
interface Store {
foo: string;
// and probably some other properties
}
interface FooProps {
foo: string;
bar: string;
}
function mapStateToProps(state: Store): Partial<FooProps> {
return {
foo: state.foo
};
}
mapDispatchToProps
A mapDispatchToProps function generates props which are used to dispatch Redux actions.
This function generally returns props which the component will use as callbacks in response to user actions.
interface FooProps {
foo: string;
addTodo: (label: string) => void;
}
function mapDispatchToProps(dispatch: any): Partial<FooProps> {
return {
// the dispatched message COULD be generated by an
// action creator instead (see later steps)
addTodo: (label: string) => dispatch({ type: 'addTodo', label })
}
}