DEV Community

Cover image for Redux - The Core Concept
Gurshehzad Singh
Gurshehzad Singh

Posted on

Redux - The Core Concept

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

{ 
  type: "LOGIN",
  payload: {
    username: "foo",
    password: "bar"
  }
}
Enter fullscreen mode Exit fullscreen mode

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

const setLoginStatus = (name, password) => {
  return {
    type: "LOGIN",
    payload: {
      username: "foo",
      password: "bar"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

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

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:

const store = createStore(LoginComponent);
Enter fullscreen mode Exit fullscreen mode

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.

class App extends React.Component {
    render() {
        return (
            <div>
                <Status user={this.props.user.name}/>
                <Login login={this.props.setLoginStatus}/>
            </div>
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.