Redux – #explainLikeIm5

I am starting a new series of blogs, which purpose is to explain complicated things in a very simple manner, like if you would have to explain it to a 5-years old. It is a good way to learn something myself and even better way to try to explain that to somebody else. If this article is NOT easy to understand, please comment below or find me on Twitter

Redux basics

What is Redux?

Redux is a state management framework that can be used with a number of different web technologies. I came across Redux while learning React. Although this framework is not being used much nowadays (Context API is used instead), it’s still worth knowing what it is.

It might not be clear in the beginning, but Redux helps giving each frontend component the exact piece of state it needs.
Even better, Redux can hold business logic inside its own layer (middleware), alongside with the code for fetching data.

Installation:

  • What Redux uses?
    There is a single state object that’s responsible for the entire state of your application.
    Let’s imagine you have React application with 10 components and each component has its own local state (10 states). Redux offers you an object called store which keeps all your states in one place.
  • How to create store?
    Redux is an object itself and it has methods we can use.
    To create store you will need to call method createStore() from Redux object:
    const store = Redux.createStore(...);
    OR if you are making project using React, you import this method from Redux first:
    import { createStore } from 'redux';
    and than use it:
    const store = createStore(...);
    Function createStore() accepts another function called reducer as an argument. Let’s find out what is that.
  • What is reducer?
    So-called reducer is a function that simply takes state as an argument and returns state:
    const reducer = (state = 5) => { return state; }
    So, full function to create store will look like this:
  • What is getState()?
    Store object has several methods we can use and getState()is one of them. You probably already figured out from its name what it does – it returns current state held by store:
    const currentState = store.getState();
  • What is action?
    Action is an object which helps Redux store to update state. It contains information about an event that has occurred. Action “tells” the store what type of event has occurred, so store knows how to update the state. Actions MUST carry type property:
    const action = { type: 'LOGIN' };
  • What is action creator?
    After creating an action, the next step is sending the action to the Redux store so it can update its state. You define action creators to accomplish this. An action creator is simply a JavaScript function that returns an action:
    const actionCreator = (action) => { return action; };
  • What is action dispatcher?
    To dispatch/deliver action to the Redux store, we use dispatch(). Calling store.dispatch() and passing the value returned from an action creator sends an action back to the store:
    store.dispatch(actionCreator());Until now our code looks like this:
  • How Redux handle action?
    After an action is created and dispatched, the Redux store needs to know how to respond to that action. This is actually a job of reducer (see paragraph 3). Together with the state, it takes action as argument. It is important to see that this is the ONLY role of the reducer. The reducer is simply a pure function that takes state and action, then returns new state:
    const state = {login: false};
    const reducer = (state, action) => {
    if(action.type === "LOGIN"){ return { login: true};
    } return state};
  • How to handle multiple actions?
    We can use switch statement to handle multiple actions in reducer. Example below:Let’s say we want to manage user authentication in Redux store. We want to have a state representation for when users are logged in and when they are logged out. We create state object with the property authenticated. We also need action creators that create actions corresponding to user login and user logout, along with the action objects themselves. This is how our code might look like:
  • What is store listener?

Another method you have access to on the Redux store object is store.subscribe(). This allows you to subscribe listener functions to the store, which are called whenever an action is dispatched in the store. One simple use for this method is to subscribe a function to your store that simply logs a message every time an action is received and the store is updated. Example:

Here we have store, reducer and dispatchers. We have also global variable count and call-back function incrementCount(). We register this function in the store like store listener. Now every time the store receives an action, our count variable increments by 1:

  • What is root reducer?
    When your application gets bigger, state might get bigger as well and you would be tempt to divide it into parts. That would break the first principle of Redux: all app state is held in a single state object in the store! BUT Redux offers a solution – multiple reducers to handle different pieces of your application’s state, then compose these reducers together into one root reducer. The root reducer is then passed into the Redux createStore() method. In order to let us combine multiple reducers together, Redux provides the combineReducers() method. This method accepts an object as an argument, in which you define properties with {key: reducer}. The name you give to the key will be used by Redux as the name for the associated piece of state. The name of reducer will be the name of your reducer function:
    const rootReducer = Redux.combineReducers({
    auth: authenticationReducer,
    notes: notesReducer
    });

Typically, it is a good practice to create a reducer for each piece of application state when they are distinct or unique in some way. For example, in our sample app, one reducer could handle authentication while another handles count incrementation:

So, this is pretty much all the basics we have learned together. It wasn’t so complex right? We know how to access the current state with getState. We know how to dispatch an action with dispatch and how to listen for state changes with subscribe.

Yet we don’t know how to couple React and Redux together, but this is a topic for another blog.

Redux is framework agnostic. You can use it with vanilla Javascript. Or with Angular. Or with React. There are bindings for joining together Redux with your favourite framework/library.
I hope you found my blog useful and helpful in your study 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s