Redux is an implementation of Flux pattern which aims to solve the state management issue in large scale complex react app.
Flux pattern at its core is pipe line:
-
- An action dispatches an event.
- Event is send at data store and triggers an mutation of the data.
- Then the data mutation triggers the view update
- User’s behaviour on view triggers more actions
React state updates triggers re-render of the view. When using Redux with React, React needs to know when state has changed in Redux. To make this happen Redux simply provides a subscribe() function to allow register event listener on state change. This is Observer pattern.
componentDidMount() { store.subscribe(() => this.forceUpdate()); }
The above code bind Redux state change with React forceUpdate function.
createStore(reducer, [initState], [enhancer]) function can be considered as an implementation of Factory pattern. it takes
-
- reducer function which describe how state should be mutated by events
- initial state
It returns a datastore object which provides
-
- getState() function which returns the current state
- dispatch(event) function witch triggers actions defined in reducer
- subscribe(listener) function witch add a listener function on state change
- replaceReducer(reducer) function which replace current reducer stored on datastore object with a new one.