How is Redux used for State Management?

Redux is a state management library that helps you better manage state in your applications. The Redux library is not specific to React. It’s a library that you can use in any other library or framework like Angular, Vue, and even vanilla JavaScript.

In Redux, you use the store to manage and track the data that’s changing in the application.

To create a store, we need to import the createStore function like this:

import { createStore } from 'redux';

The createStore function accepts three arguments:

  • the first argument is a function that is normally known as a reducer (required)
  • the second argument is the initial value of the state (optional)
  • the third argument is an enhancer where we can pass middleware, if any (optional)

Redux has four components.

  • Action: Actions are the plain JavaScript objects which are the main source of information used to send data (user interactions, internal events such as API calls, and form submissions) from the application to the store. The store receives information only from the actions. You have to send the actions to the store using store.dispatch().
  • Reducer: Actions describe the fact that something happened, but don’t specify how the application’s state changes in response. This is the job of reducers. It is based on the array reduce method, where it accepts a callback (reducer) and lets you get a single value out of multiple values, sums of integers, or an accumulation of streams of values.
  • Store: A store is a JavaScript object which can hold the application’s state and provide a few helper methods to access the state, dispatch actions and register listeners. The entire state/ object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable.
  • View: Smart and dumb components together build up the view. The only purpose of the view is to display the date passed down by the store. The smart components are in charge of the actions.