Explain Redux like I'm five

Did you find this post useful? Show some love!
DISCUSSION (22)

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 = {
  dirty: true, remainingBites: 5, color: 'red'
};

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

{
  dirty: true, remainingBites: 5, color: 'red'
}

Subscribe

Let's also subscribe to any changes to the apple:

function handleChange() {
  const currentAppleState = 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()
{
  dirty: true, remainingBites: 5, color: 'red'
}

After washing (store.dispatch(WASH);):

// store.getState()
{
  dirty: false, remainingBites: 5, color: 'red'
}
// console
Looks delicious!

After eating (store.dispatch(EAT);):

// store.getState()
{
  dirty: false, remainingBites: 3, color: 'red'
}
// console
Looks delicious!

After eating again (store.dispatch(EAT);)

// store.getState()
{
  dirty: false, remainingBites: 1, color: 'red'
}
// 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()
{
  dirty: false, remainingBites: 1, color: 'brown'
}
// 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.

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.

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...

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!

Oh, you are correct. I did rename the action at one point and missed a few spots. Thanks!

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.

Imagine standing in front of a store window. With nothing set up, the state of the window is empty. The manager wants a fancy display every morning, so you put a few fancy looking empty shelves behind the glass. Later, the manager gets the idea to show off new products when they come in, so for each type of product, you need to decide how and where to place it on one of the shelves, what to do when there are too many items, no items of a type, and so on. Let's call this the setup. This happens every day after you get to work so you can see the shelves at the beginning of the day to make this first update.

Again, the manager has something to ask you. Now, it is possible to get updates during the day on changes to the products and new items in the store, so instead of just getting a list once of all the changes, each type and each product can get a change during your shift at work. You make sure that you can either reach out to the manager or they can push over to you any kind of update for you to run through the setup you created before.

The window is the store, having the fancy shelves is an initial state, getting an update from the manager is an action, the setup are the reducers, and the process of getting the update are subscriptions.

Not exactly targeting 5 here, but hopefully a worthwhile point.

Redux is a permutation of Event Sourcing (as is Elm's Model-View-Update pattern on which Redux is based), implemented on top of React. ES has a good explanation here but from a server-side perspective.

In traditional event sourcing vernacular, Store is a view (or model), Action is an event, Reducers are event handlers which update the view, Subscriptions are just notification that an event happened, presumably so you can examine the resulting state. Redux is missing a piece to represent side effects. (e.g. calling an API) There are middlewares which have sprung up to try to handle this.

The event sourcing pattern is how the "time-traveling" debugger works (in both Redux and Elm). When the debugger is enabled, it keeps all Actions that have been dispatched, and allows you to tweak or deselect them. So if you remove an action, it reruns the reducer with all actions except that one. It's like you rewrote history. Or you can replay all but the last 5 Actions to "go back in time" by 5 steps.

Redux is a silly concept. Combination pubsub and global variable. But the author take it very seriously. Build as framework, has ability to customize and plug in. And also great tooling such as time travel.

In the end, the author prove good insight. Global variable is good for client application

My suggestion is use redux if you need time travel. If not, event emitter is much simpler

I certainly would not dismiss Redux. Sometimes the simple patterns are the most powerful, such as having one store. On the server side, the particular piece of architecture which is (almost) represented by Redux is considered one of the hardest to understand. So kudos to the author for making something hard seem trivial.

Not to say that Redux goes far enough. In comparison with a Process Manager (and with Elm), Redux is missing a baked-in representation of side effects. That would make it more or less complete.

You make a list of every friend you have and give them a number how much you like them.

Tommy: 5
Billy: 3
Sara: 2
Zak: 8

You write down all the things your friends could do, and how it would change their number.

Giving me a doll: +1
Breaking my toy-car: -2
Inviting me to a birthday: +3

Sara gives you her transformer-doll.

Now you like Sara more (+1).

Instead of striking out the number on your old list, you decide to write a new list, with the current numbers.

Tommy: 5
Billy: 3
Sara: 3
Zak: 8

You do this every time you like a friend more or less.

You keep all the old lists in your folder, so you can see which friend you liked more or less in the past.

function handleChange() {
  const currentAppleState = store.getState();
  if (currentApple.color === 'red') {
    console.log('Looks delicious!');
  } else {
    console.log('Looks awful, better throw it in the bin!');
  }
}
store.subscribe(handleChange);

if (currentApple.color === 'red') { should be if currentAppleState.color === 'red') { , right? Loved the explanation though, super straight forward.

It's a bit like you toy box.

Put toys in it, take toys out of it.

Leave toys on the floor and they get put in a trash bag and donated.

Have a cookie.

I was expecting some one to ask this long ago :)

Nice!. Now add thunks, and sagas and… oh, my! ;)

Classic DEV Post from Jun 9

How do you gain a deep understanding of your code?

Discussion on how to learn with the goal of knowing the language/framework inside out.

hemanth.hm
Just an other curious 🐜

Do you write code almost every day?

Join dev.to ❤️