DEV Community

hemanth.hm
hemanth.hm

Posted on

Explain Redux like I'm five

Top comments (26)

Collapse
 
mikkpr profile image
Mikk Pristavka • Edited

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
};
Enter fullscreen mode Exit fullscreen mode

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' };
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

To retrieve the apple object at any time, we can use store.getState(), which returns

{
  color: 'red',
  dirty: true,
  remainingBites: 5
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode

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

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

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

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

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

// store.getState()
{
  color: 'red',
  dirty: false,
  remainingBites: 1
}
// console
Looks delicious!
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
succhib profile image
Succhi

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.

Collapse
 
foresthoffman profile image
Forest Hoffman

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!

Collapse
 
mikkpr profile image
Mikk Pristavka

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

Thread Thread
 
foresthoffman profile image
Forest Hoffman

Happy to help. :)

Collapse
 
adammholloway profile image
Adam Holloway

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

Collapse
 
yashwanth2804 profile image
kambala yashwanth

Here is the working APP deployed to surge.sh Redux App like 5

Collapse
 
sambenskin profile image
Sam Benskin

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

Collapse
 
tsunaminori profile image
Tsunami Nori

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

Collapse
 
aunyks profile image
Gerald Nash ⚡️

This made perfect sense! Thank you.

Collapse
 
ivanandresdiaz profile image
Ivan Andres Diaz

I really loved it. Thank you so much

Collapse
 
v_djordje profile image
Djole

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

Collapse
 
mikkpr profile image
Mikk Pristavka

Thanks! React has already been explained here: dev.to/tiffanywismer/explain-react...

Collapse
 
yashwanth2804 profile image
kambala yashwanth

Here is the working APP deployed to surge.sh Redux App like 5

Collapse
 
rkichenama profile image
Richard Kichenama

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.

Collapse
 
ben profile image
Ben Halpern

Nice

Collapse
 
niorad profile image
Antonio Radovcic

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.

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

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.

Collapse
 
bernadusedwin profile image
bernadusedwin

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

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

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.

Collapse
 
dcsan profile image
dc

Agreed!

action creators with state objects do help time travel debug but they prevent proper typechecking, to get around JS problems. if using typescript they get in the way.

I also prefer event emitter because the pub/sub API is so much clearer.
but redux connect() does automate some processes you'd have to setup yourself otherwise
and mapStateToProps to filter which events you want to sub to.

All this could be done with a much simpler event emitter module though.
Usually when i adopt redux I'll wrap in my own TS code to hide the boilerplate in a single place.

Collapse
 
dezmathio profile image
Josiah Anjos
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.

Collapse
 
diveshjain25 profile image
DIVESH SANKHLA

Nice explanation & really helpful. This make it easy for me to learn redux after this explanation it help me to learn from the best and most recommended redux tutorials letsfindcourse.com/redux

Collapse
 
daydarkln profile image
daydarkln • Edited

In Redux, when you bite an apple, you get back an another apple bitten somebody) You can just see this apple, but actions with that will do your magic helper. Ask him (createAction) to wash them and he wash (reduce) it.

Collapse
 
kellyjandrews profile image
Kelly Andrews

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.

Collapse
 
alex_escalante profile image
Alex Escalante

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