React Redux with Hooks for beginners.
Tags: react, redux, beginners, tutorial
Published: 2020-11-29 14:09:12

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 <strong>useSelector and useDispatch </strong> hooks in our code and not <code>connect()</code>.

> 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 <strong>Context</strong>, 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,

> <strong> 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. </strong>

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](https://github.com/Gautham495/Redux-Boilerplate).

The npm packages needed are,

```js

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

```

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](https://dev-to-uploads.s3.amazonaws.com/i/zhr0mxijw8tuw2315tmf.gif)

Make a folder for 

- actions
- reducers
- types


Now lets get into the central state.

We create a <code>store.js</code> and create a global store like below,

```js

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;

``` 

- We create a central global state with <code>createStore</code>.

- Then we apply <code>applyMiddleware</code> to <code>redux-thunk</code> 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 <strong>Provider</strong> offered by react-redux to use the central store in our react app.

```js

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')
  );

```
 

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

```js

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

export default combineReducers({your_reducers});

```

- Here we combine all the reducers we would be using in all of our react application and combine it with <code>combineReducers</code> to use it to manipulate the central state.

- We will be using these reducers in <code>useSelector</code> hook later to get the central state data.

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

In types.js, you can do as below,

```js

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

```

Now lets define the action part.

Create an <strong> action folder</strong> with an <strong>action.js</strong> file in it.

```js

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

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

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


```
- 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 <strong>useDispatch</strong> in the desired place.

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

```js
   const dispatch = useDispatch()

   const budget_submit = (e) =>{

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

   dispatch(add(list))
 
  }
```
- 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 <strong>Reducer folder</strong> with the Reducer.js file in it.

```js

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

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

switch(action.type){

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

}

```

- You can see that the <strong>type</strong> which we used in action, resides here as well. 
- We initialize an empty array as initial state and check the type of action we <strong>dispatched</strong> 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 <strong>useSelector and useDispatch hooks</strong>to show a alert message with that data when a button is clicked. 

```js
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>
)
}

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

1. [React devtools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi)
2.[Redux devtools](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd)

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](https://dev-to-uploads.s3.amazonaws.com/i/yhlehzb1e9j0unhyiw9z.gif)
 

And that's how you set up a central store with,
- Types
- Actions 
- Reducers
and use that store with hooks like useSelector and useDispatch.

 
<strong>My personal experience</strong> 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!!

<strong> <u>Check out my portfolio: </u> [Gautham's portfolio](https://gautham-portfolio.netlify.app/)</strong>

<strong> <u> Check out my blog: </u>[coding-magnified.tech](https://coding-magnified.tech)</strong>


### <u>My Other Articles: </u>

- [Universal CSS properties everyone must know](https://dev.to/gautham495/universal-css-properties-everyone-must-use-4kie)

- [Create-react-app](https://dev.to/gautham495/creating-a-new-react-app-with-create-react-app-4e9m)

- [Git for beginners](https://dev.to/gautham495/basic-git-knowledge-for-beginners-m4p)

- [Change headers in react with react-helmet](https://dev.to/gautham495/changing-headers-in-react-with-react-helmet-d0d)

- [Know How to apply box-shadow on all four sides.](https://dev.to/gautham495/know-how-to-apply-box-shadow-on-all-four-sides-43pn)
 
- [Simple CSS Selectors](https://dev.to/gautham495/simple-css-selectors-for-beginners-2i44).

- [CSS Pseudo Elements](https://dev.to/gautham495/css-pseudo-elements-for-beginners-53ob).