DEV Community

Cover image for React Redux with Hooks for beginners.
Gautham Vijayan
Gautham Vijayan

Posted on • Edited on

React Redux with Hooks for beginners.

Lets learn about how to use Redux with React hooks in this post.

After having difficulties with redux, finally I can say I know how to work with it in big projects.

We will be using the useSelector and useDispatch hooks in our code and not connect().

Disclaimer:
All definitions I give here is my own version of it to make developers understand and not a very technically heavy one to scratch your head!

What is redux?

Redux is used for handling central management in React.
We can handle with State with

  • useState
  • Context API

Both have their own cons, as when the application grows big, useState will make your head spin as we have to go and change a lot of useState variables if we want to change a big portion of our code.

For Context, when ever a single state changes, the whole state re-renders which may cause problems when our application becomes big.

There are ways in which we can work around this problem but redux is more well established and maintained.

Ok now lets get into Redux's functionality.

In simpler yet effective words,

When we want to change a state, we dispatch an action which triggers a reducer function which in turn changes the state which is located in a global store/state.

This may seem too much of a overkill when you make a small project.

But the beauty of it is all of the app's functionality resides/may reside in a single file/folder and when we want to make any change, we just can get into this single file/folder and change it

It is boiler plate heavy but I will give a link to my github repo so you can use it as redux boilerplate template in all your projects.

The link to my github repo.

The npm packages needed are,


npm install redux react-redux redux-thunk redux-devtools-extension

Enter fullscreen mode Exit fullscreen mode

Now lets get into the coding part.

I will share the folder structure of the redux folder I use in all my projects, You can make yours exactly the same as the below one for coherence with this post.

Screen Recording 2020-11-29 at 06.27.29.77 PM

Make a folder for

  • actions
  • reducers
  • types

Now lets get into the central state.

We create a store.js and create a global store like below,


import {createStore,applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';
import rootreducer from './Reducer';


const initialstate={};

const middleware = [thunk];

const store = createStore(rootreducer,initialstate,composeWithDevTools(applyMiddleware(...middleware)))

export default store;

Enter fullscreen mode Exit fullscreen mode
  • We create a central global state with createStore.

  • Then we apply applyMiddleware to redux-thunk to make the action creators return a function instead of an action object.

  • We import the rootreducer and plugin with it the store.

  • Devtools extension is used here to use the redux devtools chrome extension.

Now as we have created a central store we go to index.js and include the Provider offered by react-redux to use the central store in our react app.


import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {Provider} from 'react-redux';
import Store from './Redux/Store'


ReactDOM.render(
  <Provider store={Store}>
  <React.StrictMode>
    <App />
  </React.StrictMode>
  </Provider>,
  document.getElementById('root')
  );

Enter fullscreen mode Exit fullscreen mode

Now comes the root_reducer part(Rootreducer is nothing but a naming convention to indicate that it is a central reducer). Create Reducer.js file and paste the code below,


import {combineReducers} from 'redux';
import {your_reducers} from './Reducers/Budget-reducer'

export default combineReducers({your_reducers});

Enter fullscreen mode Exit fullscreen mode
  • Here we combine all the reducers we would be using in all of our react application and combine it with combineReducers to use it to manipulate the central state.

  • We will be using these reducers in useSelector hook later to get the central state data.

After doing all these work, we are going to create Types folder and include all the types of functionalities we would be using in our react app.

In types.js, you can do as below,


export const ADD="ADD";
export const SHOW ="SHOW"

Enter fullscreen mode Exit fullscreen mode

Now lets define the action part.

Create an action folder with an action.js file in it.


import {ADD} from '../Types/Budget-types'

export const add = (data) =>dispatch=>{

 return{
    type:ADD,
    payload:{
     data
    }
 }
}


Enter fullscreen mode Exit fullscreen mode
  • Here we add the functions we would like to call when a certain action is performed in the frontend which would inturn change the state of our react app.

  • When then dispatch the action with useDispatch in the desired place.

  • An example for this can be explained, when we click a button data/state changes or any thing like that.

   const dispatch = useDispatch()

   const budget_submit = (e) =>{

   e.preventDefault();
   setlist([...list,data])

   dispatch(add(list))

  }
Enter fullscreen mode Exit fullscreen mode
  • We then include,
    • Type
    • Payload data which will be sent to the reducer to do the required work.

Now comes the last part which is reducer. Create a Reducer folder with the Reducer.js file in it.


import {ADD} from '../Types/Budget-types'

export const your_reducers = (state=[],action) =>{

switch(action.type){

 case ADD : 
 return [   
   ...action.payload.data
        ]
 default: return state
}

}

Enter fullscreen mode Exit fullscreen mode
  • You can see that the type which we used in action, resides here as well.
  • We initialize an empty array as initial state and check the type of action we dispatched with a switch case statement. -In the return statements we return the data with which we want to update the state with.

You can see that each and every functionality we think we can do in react can be done in this single reducer file itself.

Now using this redux's central state and its actions with useSelector and useDispatch hooksto show a alert message with that data when a button is clicked.

import {useDispatch,useSelector} from 'react-redux'
import Someaction from "./action"

const ButtonClick = () =>{

const dispatch =useDispatch();
const data = useSelector(state => state.your_reducer)

const click = () =>{
alert(data)
}

return (
<button onClick={click}>Click me!</button>
)
}

Enter fullscreen mode Exit fullscreen mode

You need to have this two chrome extensions to easily debug our react code:

  1. React devtools 2.Redux devtools

You can click on the redux extension and see whats really going on in our app.

It gives us the state, action and reducers info.

Screen Recording 2020-11-29 at 07.33.28.54 PM

And that's how you set up a central store with,

  • Types
  • Actions
  • Reducers and use that store with hooks like useSelector and useDispatch.

My personal experience is when you start out with redux, you will not understand any of it. So I will recommend to save my article and read it many times every day until you get a grasp over it.

That's how I learned redux and global state management in react with redux.

Thank you for reading!!

Check out my portfolio: Gautham's portfolio

Check out my blog: coding-magnified.tech

My Other Articles:

Top comments (0)