re: Explain Redux like I'm five VIEW POST

FULL DISCUSSION
 

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.

 

Great explanation! I wrote a quick demo of this working in an application, helped me understand how it all fits together - github.com/adam-m-holloway/explain...

 

Great explanation! Now you've made me want to start using redux for a new project...

 
 

many thanks for this. It made me understand the flow of redux better. haha

 

What a great Explanation! Can you do this for Explain React like I'm five, please?
Really appreciate.

 
 

That's a really awesome kicktstarter, Mikk. Kudos! I am already feeling that I should get on with Redux:)
I guess more folks who are well versed with Redux should recommend Redux courses here - hackr.io/tutorials/learn-redux - so that wannabe like me can start easily.

 

Dang, that's a fairly simple way to explain it. Well done.

When you said...

This timer starts when we first buy the apple and waits a whole week:

const weekInMilliseconds = 1000 * 60 * 60 * 24 * 7;
setTimeout(() => {
  store.dispatch(WAIT);
}, weekInMilliseconds)

I think you may have a typo where you used WAIT instead of ROT, which you defined earlier. If that's the case, you also reference it here:

Oh, right — we used setTimeout to wait for a week. Once that resolves, the WAIT action is dispatched and the resulting apple is this:

If not, never mind me.

Cheers!

 
code of conduct - report abuse