If you want to understand how Redux work, createStore(reducer)
is the core function you should know and try to implement yourself. Here is a basic example of Redux, don’t worry I will break it down later :
1 | const counterReducer = (state = 0, action) => { |
What is Reducer ?
Reducer
is a pure function, take state
and action
as parameter and return new state.
1 | const counterReducer = (state = 0, action) => { |
What is Store ?
store
, which return from createStore(reducer)
has three method, getState()
, subscribe(listener)
and dispatch(action)
1 | const createStore = (reducer) => { |
getState
getState()
is a simple function return state
1 | const getState = () => state; |
subscribe(listener)
subscribe(listener)
is a function to register listener
, it simply put listener
in a stack, in ReactJS we usually put render
function as a listener
.
1 | const subscribe = (listener) =>{ |
dispatch(action)
dispatch(action)
is a function trigger reducer
to compute new state then trigger each subscribed listener
1 | const dispatch = (action) => { |
A simple version of Redux
Combine function above we got a simple version of Redux :
1 | const createStore = (reducer) => { |
Reference
https://egghead.io/courses/getting-started-with-redux
https://github.com/reduxjs/redux/blob/master/docs/recipes/reducers/ImmutableUpdatePatterns.md