Redux - The Core Concept
Tags: react, redux, webdev, programming
Published: 2021-04-01 09:27:02

**Redux** is one of the most important and easiest concepts that developers commonly use in React world whether it be *ReactJs* or *React Native*. Lets see some of the basic concepts of Redux.

**Redux** is a JavaScript Library which helps in managing the application state. But a lot of young or newbie developers might get confused after reading this definition.

Here is a breakdown of what Redux actually is:

Redux is basically used for large scale applications. If a developer is not planning out for an application which is not largely scalable, he might want to go for Context API rather than using Redux.

***Redux has three basic principles:***

**1) Single source of truth:** We are always trying to work on a single state to store the application's data.

**2) State is Read-only:** We should never mutate the state directly and it can only be done with the use of actions which is a part of Redux.

**3) Pure Functions:** Changes in a state are only made using Pure functions. No one else can mess around with the state variables thus making all the changes secured.

***In Redux, there are 3 main areas to focus on:***

**1) Actions:** We define all the actions we need to perform for changing the state.

**2) Central Store:** Its the main place where you assume your final state is residing so that you can directly access it from here rather than doing prop drilling.

**3) Reducers:** These tell us how to or what process to follow to change the state.

***Working of Redux:***
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/44m7w4xaqhi5j6hmv5iq.jpeg)
First, we bring in the central state.
Second, we define actions to make the Redux work simpler.
Third, we build the reducer which is the brain part of our application.
Fourth, we code the components to dispatch the information.
Fifth, we write two types of Redux methods which you can use in your code.
Then, you create a Provider to give access of the store to all the components.
Finally, you create that central store.

After you get some idea of Redux, you can now understand the flow of Redux below:

**Creating Actions:**
Actions are the only way you can send data from your application to your Redux store. The data can be from user interactions, API calls, or even form submissions.

Actions are sent using the store.dispatch() method. Actions are plain JavaScript objects, and they must have a type property to indicate the type of action to be carried out. They must also have a payload that contains the information that should be worked on by the action. Actions are created via an action creator.

Here’s an example of an action that can be carried out during login in an app:
```react
{ 
  type: "LOGIN",
  payload: {
    username: "foo",
    password: "bar"
  }
}
```

This action will have an action creator like the following code:

```react
const setLoginStatus = (name, password) => {
  return {
    type: "LOGIN",
    payload: {
      username: "foo",
      password: "bar"
    }
  }
}
```
**Creating Reducers**
Reducers are pure functions that take the current state of an application, perform an action, and return a new state. These states are stored as objects, and they specify how the state of an application changes in response to an action sent to the store.

It is based on the reduce function in JavaScript, where a single value is calculated from multiple values after a callback function has been carried out.
**Example of a Reducer:**
```react
const LoginComponent = (state = initialState, action) => {
    switch (action.type) {

      // This reducer handles any action with type "LOGIN"
      case "LOGIN":
          return state.map(user => {
              if (user.username !== action.username) {
                  return user;
              }

              if (user.password == action.password) {
                  return {
                      ...user,
                      login_status: "LOGGED IN"
                  }
              }
          });
default:
          return state;
      } 
};
```
As pure functions, they do not change the data in the object passed to them or perform any side effect in the application.

**Creating the Store**
The store holds the application state. It is highly recommended to keep only one store in any Redux application.

You can create a Store with the help of a single line of code:
```react
const store = createStore(LoginComponent);
```
Actions performed on the state always return a new state. Thus, the state is very easy and predictable.

Now that we know a little more about Redux, let’s go back to our login component example that was implemented earlier and see how Redux can improve the component.
```react
class App extends React.Component {
    render() {
        return (
            <div>
                <Status user={this.props.user.name}/>
                <Login login={this.props.setLoginStatus}/>
            </div>
        )
    }
}
```
We can see that there is only one general state in the store, and each component has access to the state. This eliminates the need to continuously pass state from one component to another. You can also select the slice from the store for a particular component; this makes your app more optimized.

To summarize, Components try to dispatch an action. Action reaches to one or multiple reducers. Reducer goes to the central store which manages state of the application. When central store is changed, it sends trigger to subscription. These Subscriptions passes updated states as props to components.

Thanks for reading.