Redux version: 4.0.5 - Date April 2020
GENERAL GUIDELINE
Why Redux?: With Redux we manage a single one global store at our application and with this we can deal with the communication's limitation of unidirectional flux between father and child components.
Single source of truth: only one state
State is immutable (read-only): only an action can trigger a change, you can't do it directly
Changes are made with pure functions: only the reducers can transform the state
Redux Flow Concept
- State Data that you will consume to manipulate your interface (UI)
- UI (View) Interface that will be modified according to your state
- Actions (Dispatch) Every action that calls your reducer to mutate your state
- Reducer A function (or group of functions) that will mutate the data and send the new data to the store
- Store Holds the whole state tree of your application
Updated 23 April 2020
Installation
npm install redux
If you work into a React App, react-redux provides an easy integration. Take a look.
npm install react-redux
Creating a new store
import { createStore } from 'redux';
const store = createStore();
Creating reducers and state
The reducer will validate the action's type and then will return the new state
function yourReducer(state = 'Sii-Canada' , action){
switch(action.type){
case 'UPPERCASE':
return state.toUpperCase(); //SII-CANADA
case 'LOWERCASE':
return state.toLowerCase(); //sii-canada
default:
return state
}
}
const store = createStore(yourReducer);
Creating actions and getting updated data
An action is a generic object that by convention has the following props:
type: the function type, commonly is a string.
payload: data that we can use to update the state, here you can pass anything.
store.dispatch({type: 'UPPERCASE', payload:...}) //our action
store.subscribe(() => console.log(store.getState())) //our new data -> SII-CANADA