Explain Redux like I'm five
source link: https://dev.to/hemanth/explain-redux-like-im-five
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
I'll try to introduce the core concepts of Redux (store, actions, reducers, subscriptions) with a super simple example.
Initial state
Let's say you have an apple. The apple represents your application's current state in time. Let's define the apple as a JS object:
const initialApple = {
color: 'red',
dirty: true,
remainingBites: 5
};
Actions
There are many things you could do with the apple, and every action may change the apple slightly.
Let's define the possible actions you could perform:
const WASH = { type: 'WASH' };
const EAT = { type: 'EAT', bites: 2 };
const ROT = { type: 'ROT' };
Reducer
We can now define a reducer function to handle these actions:
function appleReducer(state = initialApple, action) {
switch(action.type) {
case 'WASH':
// sets the `dirty` field to `false`
return { ...state, dirty: false };
case 'EAT':
// decrements the number of remaining bites (cannot go below 0)
// note that the number of bites is given as a payload in the EAT action
return {
...state,
remainingBites: Math.max(0, state.remainingBites - action.bites)
};
case 'ROT':
// changes the apple's color to brown
return { ...state, color: 'brown' };
// we don't know how to handle other actions,
// so let's just do nothing and return the apple
default:
return state;
}
}
Every time we perform (or dispatch) an action, the resulting apple object is slightly different from what it was before the action.
Store
Now that we have a reducer (list of possible actions) and an initial state (the apple), let's create a store and provide the apple as the initial state:
const store = Redux.createStore(appleReducer, initialApple);
To retrieve the apple object at any time, we can use store.getState(), which returns
{
color: 'red',
dirty: true,
remainingBites: 5
}
Subscribe
Let's also subscribe to any changes to the apple:
function handleChange() {
const currentApple = store.getState();
if (currentApple.color === 'red') {
console.log('Looks delicious!');
} else {
console.log('Looks awful, better throw it in the bin!');
}
}
store.subscribe(handleChange);
Async actions
This timer starts when we first buy the apple and waits a whole week before dispatching the ROT
action:
const weekInMilliseconds = 1000 * 60 * 60 * 24 * 7;
setTimeout(() => {
store.dispatch(ROT);
}, weekInMilliseconds);
I hope you know how this works, but as a refresher: setTimeout
takes two parameters: a function and the number of milliseconds to wait. After the number has passed, the function is called.
Dispatching actions
Now, let's do stuff with the apple.
Before all the actions:
// store.getState()
{
color: 'red',
dirty: true,
remainingBites: 5
}
After washing (store.dispatch(WASH);
):
// store.getState()
{
color: 'red',
dirty: false,
remainingBites: 5
}
// console
Looks delicious!
After eating (store.dispatch(EAT);
):
// store.getState()
{
color: 'red',
dirty: false,
remainingBites: 3
}
// console
Looks delicious!
After eating again (store.dispatch(EAT);
)
// store.getState()
{
color: 'red',
dirty: false,
remainingBites: 1
}
// console
Looks delicious!
Let's forget about the apple for a while.
Oh, right — we used setTimeout
to wait for a week. Once that resolves, the ROT
action is dispatched and the resulting apple is this:
// store.getState()
{
color: 'brown',
dirty: false,
remainingBites: 1
}
// console
Looks awful, better throw it in the bin!
After washing, taking 4 bites and then waiting a week, there's not much left of the apple, but hopefully, you understood the basics of Redux.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK