|
| 1 | +Higher-order stores |
| 2 | +=================== |
| 3 | + |
| 4 | +A higher-order store is a function that turns a store creating function into a new store creating function: |
| 5 | + |
| 6 | +``` |
| 7 | +createStore => createStore' |
| 8 | +``` |
| 9 | + |
| 10 | +Look familiar? It's just like the signature for [middleware](middleware.md), only we're wrapping `createStore()` instead of `dispatch()`. |
| 11 | + |
| 12 | +Higher-order stores are a pattern for creating composable Redux extensions. They're much the same as higher-order components in React. They can be as simple as `applyMiddleware()`, or as powerful as the Redux Devtools](https://github.com/gaearon/redux-devtools). There's no limit to the kinds of things you can create. |
| 13 | + |
| 14 | +## How it works |
| 15 | + |
| 16 | +Let's look at an example. As alluded to above, `applyMiddleware()` is an example of a higher-order store. You use it by wrapping the base `createStore()` function provided by Redux: |
| 17 | + |
| 18 | +```js |
| 19 | +const newCreateStore = applyMiddleware(m1, m2, m3)(createStore); |
| 20 | +``` |
| 21 | + |
| 22 | +Internally, `applyMiddleware()` works by proxying the `dispatch()` method returned by `createStore()`: |
| 23 | + |
| 24 | +```js |
| 25 | +// Implementation has been simplified for the purpose of illustration |
| 26 | +export default function applyMiddleware(...middlewares) { |
| 27 | + // ...combine middlewares... |
| 28 | + |
| 29 | + return next => (reducer, initialState) => { |
| 30 | + const store = next(reducer, initialState); |
| 31 | + return { |
| 32 | + ...store, |
| 33 | + dispatch: middleware(store.dispatch) |
| 34 | + }; |
| 35 | + }; |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | +`next` is the next store creating function in the chain — either the return value of another higher-order store, or `createStore()` itself. |
| 40 | + |
| 41 | +This design allows multiple higher-stores can be combined simply using function composition: |
| 42 | + |
| 43 | +```js |
| 44 | +const newCreateStore = compose( |
| 45 | + applyMiddleware(m1, m2, m3), |
| 46 | + devTools, |
| 47 | + createStore |
| 48 | +); |
| 49 | +``` |
| 50 | + |
| 51 | +Now just pass your reducer (and an initial state, if desired) to your new store creating function: |
| 52 | + |
| 53 | +```js |
| 54 | +const store = createStore(reducer, intialState); |
| 55 | + |
| 56 | +<Provider store={store} /> |
| 57 | +``` |
0 commit comments