• Skip to main content
  • Skip to primary sidebar
BMA

BeMyAficionado

Inspire Affection

Getting Started With Redux And React Hooks

July 7, 2019 by varunshrivastava Leave a Comment

Before you proceed reading the article, please make sure that you are aware of the Redux Hooks. This article is going to be very short. You will be creating a ‘hello world’ application with the help of Redux and React Hooks.

I would recommend you to develop an understanding of the React Hooks first and then proceed with the article. Following video explains about the React Hooks quickly:

Introduction to React Hooks

Table of Contents

    • Setting Up Redux Store
    • Setting Up The Reducer
    • Package Structure of The Application
  • Actions and Action Creators
    • Actions
    • Action Creators
  • Redux In Action
      • ButtonGroup Component
      • HelloWorld Component
  • Conclusion

Setting Up Redux Store

If you are aware of Redux then you will know that the Store is one place where the application state is maintained. All the states reside inside of the store.

Note: If you have not used Redux before then please spend the next two hours reading and implementing what’s taught in the following article: Understanding Redux – The World’s Easiest Guide.

Let’s directly dive in the code and start by creating and initializing the Store for our Hello World application.

Below is the code for initializing the application Store.

The above code is the essence of the entire application.

For now, let’s focus on the below lines of code.

import { createStore } from 'redux';

const initialState = {tech: "React JS"};
const store = createStore(reducers, initialState);

The createStore() method creates the store Redux store. This method takes in two parameters. The first one is the Reducer (I will talk about it in a bit) the second is the initial state of your entire application.

For the sake of our example, we only need one state and that is the the tech. But you might need to add more states based on your application requirement. Anyways this thing grows gradually with your application so you do not have to worry about all the states at once.

  • Create a Shopping Cart in Java
  • LinkedList in Java using Test Driven Development

Setting Up The Reducer

The Reducer sounds scary at first but once you understand what it is, the entire concepts feel natural.

The reducer is nothing but a Pure Javascript Function. By pure it simply means that it always produces a new state.

Okay, first thing first. Here are a few concepts that you must learn before proceeding. A Reducer function is the one –

  • that gets the current state of the application from the Redux Store
  • produces a new state every time an action is dispatched.
  • decides which state is to be changed based on the action dispatched (talk about later).

Here’s the Reducer function that you will be writing for this demo application:

For now, do not stress the body of the Reducer. Simply, write a simple function that takes in the state and returns the same state back.

export default (state) => {
    return state;
}

Cool! So revisiting the Store code. Now you have a Store and Reducer setup for your application.

Let’s talk about the package structure of your application.

  • Call Server Using Ajax to fetch data using ReactJs

Package Structure of The Application

There are various ways people arrange their application. But this is one way I like to arrange the project structure of my application. I like to keep Store, Reducer and Actions in their own folder.

Folder structure for redux application.
Folder structure for Redux Application

So, for this application, please go ahead and create the above folder structure. Then simply cut and paste the Store.js file inside store folder and Reducer.js file inside reducers folder.

In the next section I will talk about the Actions and Action Creators.

Actions and Action Creators

Before reading about actions and action creators let’s do a quick revision of what you have done so far with the Store and the Reducer.

So you created a Store to.. well… store the state of the application. Then you know that this store is the holy truth of your application state. Any state present in the store is the actual state of your application at any given point in time. Therefore, you decided not to change it from everywhere so for that you created a reducer function and passed into the store.

Now the only job of this reducer function was to alter the state. So only a reducer function has the ability to alter the state of the store.

Well, so far so good. But there was one more problem. How will the reducer know which state to change and more importantly change to what?

Tada… Actions comes into the picture.

So you see how did you came into the part of actions.

Great… now let’s start with the actions.

  • How to Become a Good Programmer
  • Do You Have to be Good at Mathematics to Become a Great Programmer

Actions

Actions are the payload that you send to the store. They are a simple JSON object that contains the data produced by your application. This data is sent to the store. Actions consist of these attributes:

  • Type
  • Payload

A typical actions looks like this:

{
  type: SET_TECHNOLOGY,
  text: 'React JS is my new love'
}

If you go back to the reducer code:

You will see that the reducer uses the Action.Type to decide how to update the store with the new state: In our case it is the text is the new state that is sent from the application.

So, actions here is nothing but the payload that is used by the reducer to update the existing state of the application. I always confused actions with some kind of method. But in actual, methods are called the action creators and payload is called the action in Redux terminology.

Let’s understand about the Action Creators now.

Action Creators

The name action creator actually does what is sounds like. They are the functions that creates action. In order words – Action creators are the functions that return a JSON object containing Type and Payload.

At first this actually complicates the situation and redux kind of sound complicated. I mean I asked the question why do I have to create a function that will take in the application data and simply create an Action (payload) and return it. Why cannot I directly pass the payload to the store. Like this:

store.dispatch({type: SET_TECHNOLOGY, text: 'Some Text'});

I mean this is precise and easy to understand and it does takes away one more concept of action and action creators. But this is not the case.

In real app, you won’t be updating the state from a single place. You will updating the same state from multiple places (well that is the whole concept of using Redux) because it is a global state manager.

So, if you do not have the action and action creators then you would be breaking the DRY principle in your code. And same state would be updated from more than one place and quickly it would turn into a global mess. Therefore, the concept of Action and Action Creators actually plays a crucial role in maintaining the state of your application.

To update the state in React style, you will have to create action like this:

import * as Type from './constants';

export default function setTechnology(technology) {
    return {
        type: Type.SET_TECHNOLOGY,
        text: technology
    }
}

Put it in a separate file inside actions folder. You can name the file as you like. And do not forget to create a separate constants file to keep all the action types. You will need those constants in reducers as well.

So far you have set up a complete redux boilerplate code to proceed further and use it in your application. So, let’s stitch it all together and see it in action inside our components. And you are going to do this using the React Hooks.

Redux In Action

Go ahead and create a new HelloWorld component in the src/components folder.

I like to create folder with the same name as my Component. And then inside that folder I create a .js file with the Component name. Also, I create an index.js file to export the component. So that when I import the component in some other place in my application, I only have to write something like this:

import HelloWorld from '../../components/HelloWorld';

I find this more clean and manageable.

Yeah… so create the above component and paste below code:

I will come back to it later. Now, let’s quickly create one more component which will be used to render the buttons.

So, similarly, create another component as ButtonGroup. Paste the below code in it:

Now, let’s use both the component inside App.js file. Go ahead and paste the code inside App.js file:

Great…

So, hopefully your application is in the working state right now. So, let’s take on the pieces and stitch together. Like how it is working.

ButtonGroup Component

This component is rendered when App component is loaded in the DOM.

Three buttons are created with different text as soon as the App component is rendered. Because in the App component you have called ButtonGroup and passed the three technologies.

<ButtonGroup technologies={["React", "Angular", "Elm"]} />

On the click of the button a dispatch function is called:

<button 
        data-tech={tech} 
        key={index}
        onClick={dispatchAction}
>
       {tech}
</button>

The dispatch function then calls the Action creator to set the technology and dispatches it to the store:

const dispatchAction = (e) => {
        const tech = e.target.dataset.tech;
        console.log("Tech: " + tech);
        store.dispatch(setTechnology(tech));    
}

Now, once the action reaches the store, it is the Store’s responsibility to call the reducer function that you created at the start of this article and pass it the following action:

{
        type: Type.SET_TECHNOLOGY,
        text: technology
}

So, once it reaches to the reducer the reducer will update the store’s state accordingly.

Now, the final part where you will be updating the component on state change.

HelloWorld Component

With react hooks using the state is more than easy. You first need to import the useSelector from the react library.

import { useSelector } from 'react-redux';

And then you just need to fetch the required state from the store and pass it down. Like this:

export default function HelloWorld() {

    const tech = useSelector(state => state.tech);

    return (
        <h1>
            Say Hello To: {tech}
        </h1>
    );
}

Here, you fetched the state from the store using useSelector(state => state.tech) and passed it to the render method. So, whenever the state tech is changed the component will re-render with the latest state. That is all there is to the Redux with React Hooks.

Conclusion

Great… so it is time to wrap up this article as it has already gone beyond 1500 words.

I know it is quite confusing at first but once you hold on to it for 3 days (or week in some cases) then it feels pretty natural. The uni-directional store management concept makes state management really easy.

I know you will have many questions and I really want you to ask them here without hesitation. No matter how silly you think they sound. It is really important that you get the concept of Redux then it is really easy to implement everywhere you need to manage state and not just ReactJS.

If you are a programmer then you would love to surf following category:

  • Programming: Category

Related

Filed Under: Programming, Tutorials Tagged With: hooks, reactJS, redux

Primary Sidebar

Subscribe to Blog via Email

Do you enjoy the content? Feel free to leave your email with me to receive new content straight to your inbox. I'm an engineer, you can trust me :)

Join 874 other subscribers

Latest Podcasts

Recent Posts

  • Is The Cosmos a Vast Computation?
  • Building Semantic Search for E-commerce Using Product Embeddings and OpenSearch
  • Leader Election with ZooKeeper: Simplifying Distributed Systems Management
  • AWS Serverless Event Driven Data Ingestion from Multiple and Diverse Sources
  • A Step-by-Step Guide to Deploy a Static Website with CloudFront and S3 Using CDK Behind A Custom Domain

Recent Comments

  • Varun Shrivastava on Deploy Lambda Function and API Gateway With Terraform
  • Vaibhav Shrivastava on Deploy Lambda Function and API Gateway With Terraform
  • Varun Shrivastava on Should Girls Wear Short Clothes?
  • D on Should Girls Wear Short Clothes?
  • disqus_X5PikVsRAg on Basic Calculator Leetcode Problem Using Object-Oriented Programming In Java

Categories

  • Blogging
  • Cooking
  • Fashion
  • Finance & Money
  • Programming
  • Reviews
  • Software Quality Assurance
  • Technology
  • Travelling
  • Tutorials
  • Web Hosting
  • Wordpress N SEO

Archives

  • November 2024
  • September 2024
  • July 2024
  • April 2024
  • February 2024
  • November 2023
  • June 2023
  • May 2023
  • April 2023
  • August 2022
  • May 2022
  • April 2022
  • February 2022
  • January 2022
  • November 2021
  • September 2021
  • August 2021
  • June 2021
  • May 2021
  • April 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • April 2020
  • February 2020
  • December 2019
  • November 2019
  • October 2019
  • August 2019
  • July 2019
  • June 2019
  • May 2019
  • April 2019
  • March 2019
  • January 2019
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018
  • March 2018
  • February 2018
  • January 2018
  • December 2017
  • November 2017
  • October 2017
  • September 2017
  • August 2017
  • July 2017
  • June 2017
  • May 2017
  • April 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016

Tags

Affordable Hosting (4) algorithms (4) amazon (3) aoc-2020 (7) believe in yourself (4) best (4) database (4) earn money blogging (5) education (4) elementary sorting algorithms (4) experience (3) fashion (4) finance (6) Financial Freedom (7) food (7) friends (3) goals (5) google (5) india (10) indian cuisine (5) indian education system (4) java (16) life (16) life changing (4) love (4) make money (3) microservices (9) motivation (4) oops (4) podcast (6) poor education system (4) principles of microservices (5) problem-solving (7) programmer (5) programming (28) python (5) reality (3) seo (6) spring (3) success (10) success factor (4) technology (4) top 5 (7) typescript (3) wordpress (7)

Copyright © 2025 · Be My Aficionado · WordPress · Log in

Go to mobile version