"From the very beginning, we need to stress that Redux has no relation to React. You can write Redux apps with React, Angular, Ember, jQuery, or vanilla JavaScript." -- Redux docs
- Probably you don't! See: You Might Not Need Redux
- Your application is becomming big and you have to be constantly worried about race-conditions
- If you want to do TDD, and you want to write tests for each and every piece of your code
- You're worried about scalability of your architecture
- A redux store consists of one or more reducers
- each reducer should be responsible for only one part of the state
- each reducer is responsible for changing the state based on the dispatched action
Reducer: currentState -- action --> newState
There are two types of actions
- simple objects:
{type: 'type', data: {}}
- complex actions define by middlewares (e.g. redux-thunk:
function(dispatch, getState)
)
- dispatch one or more actions based on the current state and its input
const lightSwitch = (state = 'OFF', action) => {
switch (action.type) {
case 'TURN_ON':
return 'ON';
case 'TURN_OFF':
return 'OFF';
// Type of action is unknown therefore better not to touch the state
default:
return state;
};
};
Full example: here
Pure functions don't have side effects, and they always return the same value for a given argument. It's highly recommended to define pure function reducers.
const personObj = {
name: 'John',
address: 'Earth',
};
const changeAddress = (person, address) => {
const newPerson = {};
newPerson.name = person.name;
newPerson.address = address;
return newPerson;
};
const newPersonObj = changeAddress(personObj, 'Moon');
const personObj = {
name: 'John',
address: 'Earth',
};
const changeAddress = (person, address) => {
// We change the person address by doing this
person.address = address;
return person;
};
const newPersonObj = changeAddress(personObj, 'Moon');
- Pure functions are easy to test (ie. give them an input and be sure about the return value)
- They are good for optimization (ie. if you want to check whether or not the two person objs are different)
const person2 = changeAddress(person1);
const isSamePerson = (person1, person2) => person1 === person2;
// If changeAddress is not pure, ie. it has side-effects on person1 we need to check person1's properties to detect changes
const isSamePerson = (person1, person2) => person1.name === person2.name && person1.address === person2.address;
- Take a look at the Redux Docs
- Go through the examples (I encourage you to read their tests first)