Getting Started With Redux And React Hooks


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

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.

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.

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.

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:


  • Article By: Varun Shrivastava

  • Varun Shrivastava is an innovative full stack web developer. He is a passionate blogger and loves to write about philosophy, programming, tech and relationships. He works as a Software Developer. This is his den, you can get in touch with him here anytime you want.
  • Website Search
  • Free Ebook Download ($7.06 Value)



  • Grab the Deal Now!

    Hostgator  Starting @$3.95/mo

  • DigitalOcean Free Credits!