Redux - #explainLikeImFive
Tags: redux, webdev, codenewbie, beginners
Published: 2020-08-07 11:44:04

(Originally posted at [olenadrugalya.blog](https://olenadrugalya.blog)) 
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](https://twitter.com/OlenaDrugalya)

##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:
![Redux_install](https://dev-to-uploads.s3.amazonaws.com/i/2vj1q0c0hhe8k8dmfnte.png)

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

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

3. *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:
![Redux_createStore](https://dev-to-uploads.s3.amazonaws.com/i/xc851j5df0kvvdduleil.png)

4. *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();`

5. *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' };`

6. *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; };`

7. *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:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/y26axbwzgxghn6qac31q.png)

8. *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};`

9. *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:
![Redux](https://dev-to-uploads.s3.amazonaws.com/i/vf4837925y5p6flpobot.png)

10. *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:
![Redux_storeListener](https://dev-to-uploads.s3.amazonaws.com/i/wfsig9e8rbmpirfyjmoj.png)

11. *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: 
![Redux_rootReducer](https://dev-to-uploads.s3.amazonaws.com/i/zxo2cvk3267240plj281.png)

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 :)