How to use Redux in ReactJS with Real Life Examples – Starweaver
How to use Redux in ReactJS with Real Life Examples 1

How to use Redux in ReactJS with Real Life Examples 1

Just a quick reminder: Redux is JavaScript's predictable state container. If you want to write applications that will run in many different environments and still behave consistently, Redux is a must-have. Redux can be used with a range of JavaScript libraries and frameworks, but it has become synonymous with React lately. React is a JavaScript library used for building user interfaces. So, if you want to create a painless interactive UI, you’d definitely use React. With that said, we are going to provide a guide showcasing how to use Redux in ReactJS complete with real-life examples. Let's get started:

Essentials

Redux requires a number of dependencies

  • Redux – The core library
  • React Redux – React binding for Redux
  • Redux Thunk – Redux’s Async middleware
  • Redux DevTools Extension – This serves to link Redux DevTools to Redux app

You can npm i or yarn add them, but we’ll also use react-router-dom.

  • npm i \
  • redux \
  • react-redux \
  • redux-thunk \
  • redux-devtools-extension \
  • react-router-dom

Anyway, delete all these if you typed them in your editor. We need to start From scratch.

Examples in this guide were made in these environments:

  • Create-react-app@2.11 that was installed globally
  • Npm@641
  • Node.js 10.13.0 (LTS) but a higher version can do

Note that

A typical project involving Redux will require the below items:

Actions

An action sends your data From your app to the Redux store. For an object to qualify as an action, it must possess two properties; payload (sometimes optional) and type. The payload describes the additional data you may want to pass while the type is mostly an uppercase string (often assigned to a constant)

If were to write and delete app called TODO (the default test app in Redux and ReactJS), an Action Type would look like this: const DELETE_TODO = 'DELETE_TODO' while the action would look like this:

--------------------------------------------------------------------------------------

{

type: DELETE_TODO, payload: id,

}

Once in a while, you will need the service of action creators. An action creator, basically, is a function that serves to return an action, like this:

const deleteTodo = (id) => ({type: DELETE_TODO, payload: id})

--------------------------------------------------------------------------------------

Reducers

Reducers are functions that take two parameters each: state and action. A reducer cannot be changed and will always return a copy of the whole state. Typically, a reducer is made up of one switch statement. Here is what a Reducer looks like:

--------------------------------------------------------------------------------------

const initialState = {

todos: [

{id: 1, text: 'Eat'}, {id: 2, text: 'Sleep'},

],

loading: false,

hasErrors: false,}

function todoReducer(state = initialState, action) {

switch (action.type) {

case DELETE_TODO:

return {

...state,

todos: state.todos.filter((todo) => todo.id !==

action.payload),

}

default:

return state

}

}

--------------------------------------------------------------------------------------

Store

The store is where your Redux app lives. The store is normally initialized with a specific reducer. When applied with Redux, the comes in to wrap the app, and anything else inside the Provider can use to gain access to Redux.

--------------------------------------------------------------------------------------

import {createStore} From 'redux'

import {Provider} From 'reaс́t-redux'

import reducer From './reducers'

сconst store = createStore(reduс́er)

render(

,

document.getElementById('root'),

)

--------------------------------------------------------------------------------------

So, how do you create a ReactJS project before adding Redux on it?

Just so you understand better, we will show you how to create a todo list application - I mean heck, there’s more cool stuff we could write but a todo list is the lowest we can go.

--------------------------------------------------------------------------------------

import React From "react";

import ReactD0M From "react-dom";

import { Provider } From "react-redux";

import store From "./redux/store";

import TodoApp From "./TodoApp";

const rootElement = document.getElementById("root");

ReactDOM.render(

,

rootElement

);

--------------------------------------------------------------------------------------

The most recommended way to start new applications with Redux and React is by utilizing the official ReduxJS template for the Create React App. This takes advantage of React Redux’s integration (complete with React parts) and React Toolkit.

So, we mentioned 3 things: the official ReduxJS template, Create React App, and the Redux Toolkit. Let’s look at each more deeply:

1. Official ReduxJs Template

This is the usage of the official ReduxJS template for our Create React App

npx create-react-app my-app --template redux

2. Create React App

Here, we will show you how to create React applications with zero build configuration. The Create React App is supposed to work perfectly on both Linux, Windows, and macOS

npx create-reaс́t-app my-app

с́d my-app

npm start

In case you installed your create-react-app in global configuration through npm install -g create-react-app, we would recommend you uninstall your package via yarn global remove create-react-app or npm uninstall -g create-react-app so that npx always uses your latest version.

Also, when getting started, it is not mandatory that you configure or install tools such as Babel or webpack. They are safely preconfigured and hidden in your system so that you can put all your focus on code.

3. Creating an application

You will need Node 10.16.0 or Node 8.16.0 or later versions on your development machine. Fortunately, you don’t need any of that on the server. Use nvm-windows or nvm (Linux/macOS) to switch different versions of Node between different projects.

Now, to create a new application, choose one of these techniques:

--------------------------------------------------------------------------------------

npx

Type:

npx create-react-app my-app

The npx runner tool comes with npm 5.2 or higher

or

Yarn

Type

yarn create-react-app my-app

You will only find yarn create can only be found in 0.25 or higher

Npm

Type:

npm init react-app my-app

You need npm 6+ to use npm init

Let’s Create a ReactJS Project add Redux to It

First off, let's create a new react application then add cd into it before starting it:

create-react-app reӓct-redux-tutorial

cd reӓct-redux-tutoriӓl

npm start

It is evident from the above code that create-react-app delivers a basic template complete with a paragraph, official ReactJS icons rotating, and an anchor to the React website. So, what did we create with the above code? A rotating ReactJS logo!

At times, you want to make the code lightweight and easy to grasp. That’s also what you would do if you wanted a more complex result. So let’s use Redux to stop and start the above logo. We will add these Redux packages:

npm install --save redux react-redux

Just a quick reminder, again:

redux v4.0.1

  • Basically, Redux delivers the global state your entire application needs so that it can be used by any component.
  • There can only be one state for the entire app rather than each of the components
  • It’s basically a state management library

react-redux v5.11

  • This is often used to gain access to data contained in Redux and make modifications on it by sending appropriate actions to Redux
  • It allows React components to read and interpret data from Redux’s store and dispatch appropriate actions to update data in the store.

So, let's stop and start our React logo from spinning.

If you are running on Linux/Mac system, proceed this way:

mkdir src/actions

touch src/ӓctions/startaction.js

touch src/ӓctions/stopaction.js

If you are running on Windows environment, proceed this way:

mkdir src\ӓctions

echo "" > src\ӓctions\startAction.js

echo "" > src\ӓctions\stopAction.js

Great, now let’s do some editing on src/actions/startAction.js this way:

--------------------------------------------------------------------------------------

export const startAction = {

type: "rotate",

payload: true

};

--------------------------------------------------------------------------------------

Looks nice! Now let’s tell the reducer that the action type we want is the rotation (rotate) of our React logo. Note that for you to rotate the React logo, you need to change the state of the object to true.

We will proceed to edit src/actions/stopAction.js like this:

--------------------------------------------------------------------------------------

export const stopAction = {

type: "rotate",

pӓyload: false

};

--------------------------------------------------------------------------------------

We are going to let our reducer know that the action type we want on the React logo is rotation (rotate). So, the state of React logo has to change to false.

Let’s prepare a reducer for our application:

In Mac/Linux, proceed like this:

mkdir src/reducers

touch src/reducers/rotӓteReducer.js

In Windows, proceed like this:

mkdir src\reducers

echo "" > src\reducers\rotӓteReducer.js

Finish by adding this code inside the above code:

--------------------------------------------------------------------------------------

export default (stӓte, action) => {

switch (ӓction.type) {

case "rotate":

return {

rotating: action.payload

};

default:

return state;

}

};

--------------------------------------------------------------------------------------

The default case has been added in this code to keep the state same and unaltered if the type of action is not set as rotate.

The last thing we need to perform is to establish a store for the entire app. And since there is just one state/one store, we don’t need to create a whole folder for it. With that being said, proceed this way:

Mac/Linux

touch src/store.js

Windows

echo "" > src\store.js

WATCH LIVE CLASSES FREE

Learn from Leading Experts | Learn by Doing

Individual Sign-up
Register a Team
(with discounts)

Save even more for teams!
Find out more...

 

Current Streaming Courses

"The secret to getting ahead is getting started..." ~ Mark Twain