Redux And New React-Redux Hooks

If you are a React developer, you must have heard of Redux for sure. While Redux is such an important tool for React developers, it also introduces extra code and a cumbersome setup. However, with the popularity of functional components and hooks, Redux also introduces some useful hooks for developers to work with. This has made working with Redux somewhat easier than before.

Let’s first have a brief introduction to Redux and its architecture.

What is Redux

The classic definition of redux is a predictable state management library. But, do you ever wonder what that really means. let us see in simple terms what it really means.

Why do we need it

The main purpose of creating redux is state management. What is the state? Here, the state means the global state of the application. The change in the global state can affect most parts of your application.
Redux is a centralized container that holds the state of the application. Because of this, you can tell the state of the application at any given time, thus redux is said to be predictable.

Redux structure

Redux has 3 major building blocks

  • Store: JavaScript Object that holds the state of the application.
  • Actions: Plain JS objects that carry events
  • Reducer : pure functions that act as “event handlers” `. There can be one or more reducers for updating a slice of the store.

Redux store is immutable meaning that we cannot directly change or modify the store.
For example,
store.username = { name: “James” }
The above assignment is not possible in redux.
Then, how can we change the state? The Answer is Reducer

Ex:

function SampleReducer( store, action ){
    //create a copy of the store.  Spread operator is used to copy the existing store   
    const upDatedStore = { …store }; 
    /*any modification on upDatedStore */
    return upDatedStore;    //return  the updated/modified the state    
}

You can notice in the above reducer function, there are two parameters.
One represents the current** state( store )**, the other is the *action*.

Why do we need the action parameter?
Action parameter tells what properties of the store are going to be changed. Basically, actions are events that is tells what changes are needed in the store.

How should you initiate an action?
The Store has a dispatch function for this.

Ex: store.dispatch( myaction )

It is the responsibility of the store’s dispatch method to call the appropriate reducer. The reducer then would take the action, change the state, and return it. This change in the state of the store would consequently update the UI components of the application.

React-redux hooks

Before the introduction of React hooks, setting up Redux with react was somewhat cumbersome. However, new hooks in a react-redux library have made Redux less complicated to set up and work with.

Let us see some common hooks you can use in your next React project.

useSelector()

  • extract data from the Redux store state
  • can call multiple times within a single functional component
  • equivalent to the mapStateToProps

Ex:
Imagine you have a redux store initialized in your reducer with the following state.

state = { business : [] };

you can access the state as follows, for example, in App.js

import React from 'react'
import { useSelector } from 'react-redux'

export const SampleFunctionalComponent = () => {
  const  business = useSelector((state) => state.business )
  return <div>{ business }</div>
}

useDispatch()

const dispatch = useDispatch()

This hook return a reference to dispatch function ( store.dispatch()) of the store.
In many react-redux web applications, you would organize your actions and action creators in a separate folder. Assume you have the following action creator in business.js.

import * as api from '../api';

export const getBusinsessInfo = (search) => async (dispatch)=>{

    try{

       const { data } =  await api.fetchBussinessInfo(search);
       dispatch( { type : 'FETCH_ALL', payload: data } );
    }catch(error){
        console.log( error );
    }


}

Now, in App.js, to use this action, you can use useDispatch() hook.

import { getBusinsessInfo } from './actions/bussiness';
import { useDispatch } from 'react-redux';


useEffect(()=>{    
    dispatch( getBusinsessInfo({ ‘resturant’, ‘Los Angeles’ }));
},[dispatch]);

useStore()

returns a reference to the store.

import React from 'react'
import { useStore } from 'react-redux'

export const SampleFunctionalComponent = () => {
  const store = useStore()


  return <div>{store.getState()}</div>
}

With my experience working with React and Redux, the most useful React-Redux hooks are useSelector() and useDispatch().

Conclusion

In this brief article, I introduce you to React-Redux hooks that you can use in your next single-page web application. For more details, you can check out the official documentation on redux hooks here.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top