# Getting Started With Redux: Why Redux?

When you're learning React, you will almost always hear people say how great Redux is and that you should give it a try. The React ecosystem is growing at a swift pace, and there are so many libraries that you can hook up with React, such as flow, redux, middlewares, mobx, etc.

Learning React is easy, but getting used to the entire React ecosystem takes time. This tutorial is an introduction to one of the integral components of the React ecosystem—Redux.

## Basic Non-Redux Terminology

Here are some of the commonly used terminologies that you may not be familiar with, but they are not specific to Redux per se. You can skim through this section and come back here when/if something doesn't make sense.

### Pure Function

A pure function is just a normal function with two additional constraints that it has to satisfy:

1. Given a set of inputs, the function should always return the same output.
2. It produces no side effects.

For instance, here is a pure function that returns the sum of two numbers.

 1 /* Pure add function */  2 const add = (x,y) => {  3  return x+y;  4 }  5   6 console.log(add(2,3)) //5  7

Pure functions give a predictable output and are deterministic. A function becomes impure when it performs anything other than calculating its return value.

For instance, the add function below uses a global state to calculate its output. In addition, the function also logs the value to the console, which is considered to be a side effect.

 1 const y = 10;  2 3 const impureAdd = (x) => {  4  console.log(The inputs are ${x} and${y});  5  return x+y;  6 } 

### Observable Side Effects

"Observable side effects" is a fancy term for interactions made by a function with the outside world. If a function tries to write a value into a variable that exists outside the function or tries to call an external method, then you can safely call these things side effects.

However, if a pure function calls another pure function, then the function can be treated as pure. Here are some of the common side effects:

• making API calls
• logging to console or printing data
• mutating data
• DOM manipulation
• retrieving the current time

### Container and Presentational Components

Splitting the component architecture into two is useful while working with React applications. You can broadly classify them into two categories: container components and presentational components. They are also popularly known as smart and dumb components.

The container component is concerned with how things work, whereas presentational components are concerned with how things look. To understand the concepts better, I've covered that in another tutorial: Container vs. Presentational Components in React.

### Mutable vs. Immutable Objects

A mutable object can be defined as follows:

mutable object is an object whose state can be modified after it is created.

Immutability is the exact opposite—an immutable object is an object whose state cannot be modified after it is created. In JavaScript, strings and numbers are immutable, but objects and arrays are not. The example demonstrates the difference better.

 1 /*Strings and numbers are immutable */  2 3 let a = 10;  4 5 let b = a;  6 7 b = 3;  8 9 console.log(a = ${a} and b =${b} ); //a = 10 and b = 3  10 11 /* But objects and arrays are not */  12 13 /*Let's start with objects */  14 15 let user = {  16  name: "Bob",  17  age: 22,  18  job: "None"  19 }  20 21 active_user = user;  22 23 active_user.name = "Tim";  24 25 //Both the objects have the same value  26 console.log(active_user); // {"name":"Tim","age":22,"job":"None"}  27 28 console.log(user); // {"name":"Tim","age":22,"job":"None"}  29 30 /* Now for arrays */  31 32 let usersId = [1,2,3,4,5]  33 34 let usersIdDup = usersId;  35 36 usersIdDup.pop();  37 38 console.log(usersIdDup); //[1,2,3,4]  39 console.log(usersId); //[1,2,3,4] 

To make objects immutable, use the Object.assign method to create a new method or the all new spread operator.

 1 let user = {  2  name: "Bob",  3  age: 22,  4  job: "None"  5 }  6 7 active_user = Object.assign({}, user, {name:"Tim"})  8 9 console.log(user); //{"name":"Bob","age":22,"job":"None"}  10 console.log(active_user); //{"name":"Tim","age":22,"job":"None"} 

## What Is Redux?

The official page defines Redux as follows:

Redux is a predictable state container for JavaScript applications.

Although that accurately describes Redux, it's easy to get lost when you see the bigger picture of Redux for the first time. It has so many moving pieces that you need to fit together. But once you do, I promise you, you'll start loving Redux.

Redux is a state management library that you can hook up with any JavaScript library, and not just React. However, it works very well with React because of React's functional nature. To understand this better, let's have a look at the state.

As you can see, a component's state determines what gets rendered and how it behaves. The application has an initial state, and any user interaction triggers an action that updates the state. When the state is updated, the page is rerendered.

With React, each component has a local state that is accessible from within the component, or you can pass them down as props to child components. We usually use the state to store:

1. UI state and transitionary data. This includes a list of UI elements for navigation menu or form inputs in a controlled component.
2. Application state such as data fetched from a server, the login state of the user, etc.

Storing application data in a component's state is okay when you have a basic React application with a few components.

However, most real-life apps will have lots more features and components. When the number of levels in the component hierarchy increases, managing the state becomes problematic.

## Why Should You Use Redux?

Here is a very probable scenario that you might come across while working with React.

1. You are building a medium-sized application, and you have your components neatly split into smart and dumb components.
2. The smart components handle the state and then pass them down to the dumb components. They take care of making API calls, fetching the data from the data source, processing the data, and then setting the state. The dumb components receive the props and return the UI representation.
3. When you're about to write a new component, it's not always clear where to place the state. You could let the state be part of a container that's an immediate parent of the presentational component. Better yet, you could move the state higher up in the hierarchy so that the state is accessible to multiple presentational components.
4. When the app grows, you see that the state is scattered all over the place. When a component needs to access the state that it doesn't immediately have access to, you will try to lift the state up to the closest component ancestor.
5. After constant refactoring and cleaning up, you end up with most of the state holding places at the top of the component hierarchy.
6. Finally, you decide that it's a good idea to let a component at the top handle the state globally and then pass everything down. Every other component can subscribe to the props that they need and ignore the rest.

This is what I've personally experienced with React, and lots of other developers will agree. React is a view library, and it's not React's job to specifically manage state. What we are looking for is the Separation of Concerns principle.

Redux helps you to separate the application state from React. Redux creates a global store that resides at the top level of your application and feeds the state to all other components. Unlike Flux, Redux doesn't have multiple store objects. The entire state of the application is within that store object, and you could potentially swap the view layer with another library with the store intact.

The components re-render every time the store is updated, with very little impact on performance. That's good news, and this brings tons of benefits along with it. You can treat all your React components as dumb, and React can just focus on the view side of things.

Now that we know why Redux is useful, let's dive into the Redux architecture.

## The Redux Architecture

When you're learning Redux, there are a few core concepts that you need to get used to. The image below describes the Redux architecture and how everything is connected together.

If you're used to Flux, some of the elements might look familiar. If not, that's okay too because we're going to cover everything from the base. First, make sure that you have redux installed:

 1 npm install redux 

Use create-react-app or your favorite webpack configuration to set up the development server. Since Redux is an independent state management, we're not going to plug in React yet. So remove the contents of index.js, and we'll play around with Redux for the rest of this tutorial.

## Store

The store is one big JavaScript object that has tons of key-value pairs that represent the current state of the application. Unlike the state object in React that is sprinkled across different components, we have only one store. The store provides the application state, and every time the state updates, the view rerenders.

However, you can never mutate or change the store. Instead, you create new versions of the store.

 1 (previousState, action) => newState 

Because of this, you can do time travel through all the states from the time the app was booted on your browser.

The store has three methods to communicate with the rest of the architecture. They are:

• Store.getState()—To access the current state tree of your application.
• Store.dispatch(action)—To trigger a state change based on an action. More about actions below.
• Store.subscribe(listener)—To listen to any change in the state. It will be called every time an action is dispatched.

Let's create a store. Redux has a configureStore method to create a new store. You need to pass it a reducer, although we don't know what that is. So I will just create a function called reducer. You may optionally specify a second argument that sets the initial state of the store.

#### src/index.js

 1 import { configureStore } from "redux";  2 // This is the reducer  3 const reducer = () => {  4 /*Something goes here */  5 }  6 7 //initialState is optional.  8 //For this demo, I am using a counter, but usually state is an object  9 const initialState = 0  10 const store = configureStore(reducer, initialState); 

Now we're going to listen to any changes in the store, and then console.log() the current state of the store.

 1 store.subscribe( () => {  2  console.log("State has changed" + store.getState());  3 }) 

So how do we update the store? Redux has something called actions that make this happen.

## Action/Action Creators

Actions are also plain JavaScript objects that send information from your application to the store. If you have a very simple counter with an increment button, pressing it will result in an action being triggered that looks like this:

 1 {  2  type: "INCREMENT",  3  payload: 1  4 } 

They are the only source of information to the store. The state of the store changes only in response to an action. Each action should have a type property that describes what the action object intends to do. Other than that, the structure of the action is completely up to you. However, keep your action small because an action represents the minimum amount of information required to transform the application state.

For instance, in the example above, the type property is set to "INCREMENT", and an additional payload property is included. You could rename the payload property to something more meaningful or, in our case, omit it entirely.  You can dispatch an action to the store like this.

 1 store.dispatch({type: "INCREMENT", payload: 1}); 

While coding Redux, you won't normally use actions directly. Instead, you will be calling functions that return actions, and these functions are popularly known as action creators. Here is the action creator for the increment action that we discussed earlier.

 1 const incrementCount = (count) => {  2  return {  3  type: "INCREMENT",  4  payload: count  5  }  6 } 

So, to update the state of the counter, you will need to dispatch the incrementCount action like this:

 1 store.dispatch(incrementCount(1));  2 store.dispatch(incrementCount(1));  3 store.dispatch(incrementCount(1)); 

If you head to the browser console, you will see that it's working, partially. We get undefined because we haven't yet defined the reducer.

So now we have covered actions and the store. However, we need a mechanism to convert the information provided by the action and transform the state of the store. Reducers serve this purpose.

## Reducers

An action describes the problem, and the reducer is responsible for solving the problem. In the earlier example, the incrementCount method returned an action that supplied information about the type of change that we wanted to make to the state. The reducer uses this information to actually update the state. There's a big point highlighted in the docs that you should always remember while using Redux:

Given the same arguments, a Reducer should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.

What this means is that a reducer should be a pure function. Given a set of inputs, it should always return the same output. Beyond that, it shouldn't do anything more. Also, a reducer is not the place for side effects such as making AJAX calls or fetching data from the API.

Let's fill in the reducer for our counter.

 1 // This is the reducer  2 3 const reducer = (state = initialState, action) => {  4  switch (action.type) {  5  case "INCREMENT":  6  return state + action.payload  7  default:  8  return state  9  }  10 } 

The reducer accepts two arguments—state and action—and it returns a new state.

 1 (previousState, action) => newState 

The state accepts a default value, the initialState, which will be used only if the value of the state is undefined. Otherwise, the actual value of the state will be retained. We use the switch statement to select the right action. Refresh the browser, and everything works as expected.

Let's add a case for DECREMENT, without which the counter is incomplete.

 1 // This is the reducer  2 3 const reducer = (state = initialState, action) => {  4  switch (action.type) {  5  case "INCREMENT":  6  return state + action.payload  7  case "DECREMENT":  8  return state - action.payload  9  default:  10  return state  11  }  12 } 

Here's the action creator.

 1 const decrementCount = (count) => {  2  return {  3  type: "DECREMENT",  4  payload: count  5  }  6 } 

Finally, dispatch it to the store.

 1 store.dispatch(incrementCount(4)); //4  2 store.dispatch(decrementCount(2)); //2 

That's it!

## Summary

This tutorial was meant to be a starting point for managing state with Redux. We've covered everything essential needed to understand the basic Redux concepts such as the store, actions, and reducers. Towards the end of the tutorial, we also created a working redux demo counter. Although it wasn't much, we learned how all the pieces of the puzzle fit together.

Over the last couple of years, React has grown in popularity. In fact, we have a number of items in the marketplace that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out.

In the next tutorial, we will make use of the things we've learned here to create a React application using Redux. Stay tuned until then. Share your thoughts in the comments.