dispatch
is the function attached to the Redux store that calls the reducer and updates all subscribed listeners to the store (eg if you attach it to React via react-redux, there is a listener for each connected component), then returns the action (important for debugging). If you didn’t have it then you would have to get the store, pass it into the reducer function along with an action, then manually updates all listeners. Which is what dispatch
does, so you’d just be replacing dispatch with dispatch.
The reducer can be any function as as long as it accepts the state + an action and returns a new state. dispatch
is defined in the Redux code, it gets created when createStore
is called. It doesn’t know anything about what your state looks like, it’s just there to attach the reducer to the store and allow it to be used
Edit: this is a slightly simplified version of Redux (and I mean slightly, this should be fully functional):
function createStore(reducer) {
let currentState;
let listeners = [];
return {
getState() {
return currentState;
},
subscribe(listenerFunction) {
listeners.push(listenerFunction);
return function unsubscribe() {
const index = listeners.indexOf(listenerFunction);
listeners.splice(index, 1);
}
},
dispatch(action) {
currentState = reducer(currentState, action);
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i];
listener();
}
return action;
}
};
}
In the actual code there’s some error handling which adds quite a lot of extra code. And there’s ability to replace reducers + ability to add initial state + ability to apply middleware + support for a pattern called Observables, all of which are four or five lines of code each. But the above is the core of Redux, that’s it.
You run the createStore function and pass it the reducer – const store = createStore(myReducer)
. It returns an object with three methods, so:
-
store.getStore()
will give you the current state directly. -
store.subscribe(myListener)
will add a listener function that will run every time the store updates (for example, a function that gets the store and returns a specific field). -
store.dispatch(myAction)
will run the reducer to update the current state and notify all the listeners.