DEV Community

Cover image for A Simple Introduction to Redux!
Anurag Gharat
Anurag Gharat

Posted on

A Simple Introduction to Redux!

If you have you ever made a JavaScript application chances are you would have come across a time when handling the state of your application would have become unmanageable. In this case you would have looked for state management libraries and left it learning halfway as it was complex and difficult. So this is a small tutorial for you to learn the basics of Redux and what you need for it as a prerequisite?? Nothing!! Just basics of JavaScript and a code editor offcourse!

What is Redux ? And why do we need it?

Redux is a predictable state container for JS apps, that’s what the documentation says. But to understand it in a simpler way

Redux is a State management Library for managing state of JavaScript apps on the Front-End

Redux provides us a central store where you can store the state of the app and extract it an any component of the app. As Redux is a State Management Library you can use it with any of your preferred Front-End framework like React, Angular, Vue or even with bare minimum JavaScript app.

As our JavaScript apps grows bigger and more components are added to it, at some point it becomes difficult to manage the central state of the apps and keeping all states in sync. That’s where Redux comes to the rescue. In normal apps let’s say in a React-App you would have to manage state on a component level and pass it via props in all child components that would consume the state. In Redux you maintain a central state of the app (redux store) and any component can access it at any level. Every component has the power to change the state of the store and the resulting action will lead to change in the states of all the component that consumes the central state.

Getting Started

So first things first, create a folder by any name of your choice and open it in your code editor. Now open the terminal in you project folder and initialize a package.json using the following command.

npm init -y
Enter fullscreen mode Exit fullscreen mode

The “y” stand as a yes for all. Now as our project folder is ready we will go on to install redux in it.

npm i redux
Enter fullscreen mode Exit fullscreen mode

Now create a index.js file and type console.log(“Hello World”) in it and run the file from the terminal using node index.js to test if its working.
I am assuming you have node installed on your machine. If not go onto the official docs and install it , its a pretty straight forward process.

Understanding the Principles of Redux:

The entire concept of redux depends on these three important principles:

  1. The entire state of your application lies inside the redux store.
  2. The only way to change the state inside the store is by emitting an action.
  3. The reducers are pure functions that specify how the state should change.

Writing your First Redux Application

const redux = require('redux');
Enter fullscreen mode Exit fullscreen mode

So in your index.js file add this statement at the top which imports *redux * as **redux **in our file.

Set the initial state of app:

The initial state of our app is an object that has all the central data of our app. In this example the initial state of our app is

const initialState={
    friends:255,
    online:false,
    newMessages:6
}
Enter fullscreen mode Exit fullscreen mode

Add this code below the import.

Create a reducer and pass the initial state to it:

A Reducer is a function that takes intialstate and action as parameters and returns the copy of modified state. Reducer is responsible for handling and changing the state of the application. What change must be made and what state must be set is defined by the action that is provided to it. The Reducer always returns the copy of the modified state. Reducer is a function consisting of switch cases for determining types of actions. Here we check the action type and return the changed state. Action is an object with type as an attribute, we will understand it next.

const reducer=(state=initialState, action)=>{
    switch (action.type) {
      case 'IS_ONLINE':
        return {
          ...state,
          online: true,
        };
      case 'ADD_A_FRIEND':
        return {
          ...state,
          friends: state.friends+1,
        };
      case 'READ_A_MESSAGE':
        return {
          ...state,
          newMessages: state.newMessages-1,
        };
      default:
        return state
    }
}
Enter fullscreen mode Exit fullscreen mode

Action Creators:

Action creator are functions that return an Action, and an Action is nothing but an object with a type and payload as attributes. The Action type determines what change in data should be made by the reducer and with payload you can pass the data object that your central state might need.
For Example: If in application your user logs in, you would create an action of type ‘USER_LOGGEDIN’ and pass the User’s Id or User Details with the payload . Now the reducers receives this payload and in the central state adds User’s Details . So now your entire application can access the User’s Details. As our application is small we won’t be using payload.

function isOnline(){
    return {
        type:'IS_ONLINE'
    }
}
function addFriend() {
    return {
        type: "ADD_A_FRIEND",
  };
}function readMessage() {
    return {
        type: "READ_A_MESSAGE",
  };
}
Enter fullscreen mode Exit fullscreen mode

Create your Store:

As discussed earlier the entire central state tree of your application lies inside the store. Here we create a state tree of our application with createStore method and store it with variable store. We pass our reducer to the store so that it can access it.

const store=redux.createStore(reducer)
Enter fullscreen mode Exit fullscreen mode

A store has various methods such as

getState():-
The getState() method returns the instance of the state. Here we call it before passing any action so it prints the initial state of our application.

console.log(store.getState())
Enter fullscreen mode Exit fullscreen mode

subscribe():-
The store.subscribe() method subscribes us to a store and adds an onchange event listener. In simple words on every change the subscribe method will call a function passed as an argument. Here we log a statement on the console every time our state changes.

const changeListner = store.subscribe(()=>(console.log("state updated",store.getState())))
Enter fullscreen mode Exit fullscreen mode

dispatch() :-
The dispatch method dispatches actions attributing the store. It triggers the state change with the action creator passed on to it. Here we are dispatching various action creators to alter the state. For every dispatch method we will get a logged statement on our console showing the state at that instance.

store.dispatch(isOnline())
Enter fullscreen mode Exit fullscreen mode

So this is how our index.js file looks like after we implement all of the above steps.

const redux = require("redux");

const initialState={
    friends:255,
    online:false,
    newMessages:6
}

const reducer=(state=initialState,action)=>{
    switch (action.type) {
      case 'IS_ONLINE':
        return {
          ...state,
          online: true,
        };
      case 'ADD_A_FRIEND':
        return {
          ...state,
          friends: state.friends+1,
        };
      case 'READ_A_MESSAGE':
        return {
          ...state,
          newMessages: state.newMessages-1,
        };
      default:
        return state
    }
}

function isOnline(){
    return {
        type:'IS_ONLINE'
    }
}
function addFriend() {
    return {
        type: "ADD_A_FRIEND",
  };
}function readMessage() {
    return {
        type: "READ_A_MESSAGE",
  };
}

const store=redux.createStore(reducer)
console.log("-----------------------------------")
console.log("Initial State of Application",store.getState())
console.log("-----------------------------------");
const changeListner = store.subscribe(()=>(console.log("state updated",store.getState())))

console.log("GO ONLINE")
store.dispatch(isOnline())

console.log("Add a Friend");
store.dispatch(addFriend())

console.log("Add a Friend");
store.dispatch(addFriend());

console.log("Read a message");
store.dispatch(readMessage());

console.log("Read a message");
store.dispatch(readMessage());

changeListner()

Enter fullscreen mode Exit fullscreen mode

Now go on to the terminal and run your application using

node index.js 
Enter fullscreen mode Exit fullscreen mode

This must be the output that you receive.

Final Output of Redux

So now I am guessing you have understood the basic concepts of redux! Now go ahead and use it in your next project

Thank you for reading! Share if this blog helped you in understanding Redux. I post regular content on Web Development on Twitter. If you are interested in such content, make sure you follow me on anuraggharat.

Top comments (1)

Collapse
 
ixpsych29 profile image
Muhammad Abdullah Ibn Rafique

Well Written Buddy!