Redux is a state management library, an application data-flow architecture to be specific
Redux uses a store object that store all state required by an application and needed to be passed on to your project components
Important Redux methods
Redux.createStore()
- The create store method is used to create a store object for your redux program which will be exported and used in other components for state management
- The createStore(reducer) takes in a reducer as an argument (discussed below)
- An optional argument passed to the createStore method is the Redux.middleWare() method which is used to handle async functions
const store = Redux.createStore(reducer)
const reducer = ()=>{}
- The reducer is a function used in redux that takes in state and actions as parameters and always returns a state(either updated or same if the conditions of the state rendering are met).
- Most preferrably use a
switch(){case}
statement for conditional rendering of the state to be passed to the store
const reducer = (state=defaultState, action)=>{
switch(action.type){
case CASE1:
return state
default:
return state
}
}
store.dispath()
- The .dispatch() method is used to throw in actions to the store created using the redux createStore method
- Takes in an action object type as the parameter or most preferrably takes in a action creator as an argument to make your code simple and more readable
- Can optionally take in a callback as a second argument, but the callback is most prefarrably placed inside a function which is added as a parameter in the
.subscribe(callback)
method.
store.dispatch(action creator)
store.subscribe(callback)
- A special redux method that adds a listener to a store
- Determines what a your program should execute immediately after a state is updated in the reducer
- Takes in a callback function created as an argument
Redux.combineReducer()
- This redux method combines multiple reducers in a redux file that will be used in the createStore method which can only be called once
- Takes in an object with key value pairs of reducers as an argument
const reducers = Redux.combineReducers({
redu1 : nameOfReducer,
redu2 : nameOfReducer
})
store.getState
- This method is used in getting the current state of a redux store
const result = store.getState()