Structuring Redux in a React Web App
Tags: beginners, react, redux, reduxthunk
Published: 2021-03-09 16:17:59

---
title: Structuring Redux in a React Web App 
published: true
description: A quick rundown on how to structure the basic react-redux boilerplate code.
tags: beginner, react, redux, reduxthunk,
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/svgs4orqh1s78oyxrpam.png
---

## What is Redux?
Redux is a state management tool used when building complex web applications using javascript frameworks. React-Redux is built specifically for react framework, it is maintained by the Redux team.

### Why is React-Redux so important?
State management tool like React-Redux is necessary when building large or complex applications that require a consistent data structure that represents the state of your app that you can read from and write to. It makes passing data across components easily traceable.

### Do you need it?
If you're building web portals or any data intensive web app, Yes, you'll need it to manage the data sent and received from the server per time.

#### What this article is and what not
It is NOT to explain fully what React-Redux is. To learn about react-redux, check this [Link](https://blog.logrocket.com/why-use-redux-reasons-with-clear-examples-d21bffd5835/)

**It is to show how to set up and structure the react-redux for easy use.** _Basically, the boilerplate code you need to get started._

## Let's Get Started

There are three major components of React-Redux
* store
* actions
* reducers

Store - as the name implies, it's like a storehouse that house all our data. That is, where all our states are stored.

Actions - as the name implies, actions are the instructions the user issue to the redux to either write or fetch data from the store. They are objects with two major properties: `{type: "DO_THIS", payload: dataObject}`.

Reducers - reducers are functions that take actions from the application, perform an action and return a new state based on the action passed into it.

### Install basic dependencies
`npm i redux react-redux redux-thunk`

* create a store folder in your /src directory

In `/src/store`, add an index.js file to the store folder
In `/src`, add Actions folder
In `/src`, add Reducers folder

It should look something like: 
![store folder structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sbsxma1cnpqknecjynmd.PNG)

* In `/src/actions/`, action files are created according to modules so as to group similar concerns. For example, 
`AuthenticationActions.js` - may contain `signInAction();` `logoutAction();` 
`BlogActions.js` - may contain `getBlogPostAction();` `deleteCommentAction();` `updateBlogPostAction();` etc..

For this example, we'll create a TestAction.js file that fetches users from `https://jsonplaceholder.typicode.com/users`

In `/src/actions/TestAction.js`,
```
export const getAllPosts = () => {
  return (dispatch) => {
    //   fetch placeholder data from jsonplaceholder
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => response.json())
      .then((result) =>
        //dispatch response to the store
        dispatch({ type: "DO_THIS", payload: result })
      );
  };
};
```

In `/src/reducer/`, create TestReducer.js file, several reducers can be created to handle the state for specific modules within our application.
Create a Test Reducer function that accepts two parameters, 
	- state (with the default set to its original state) and action
	- Use switch to check action type and then update state.

In `/src/reducer/TestReducer.js`
```
const initialState = {
  users: null,
};

export default function TestReducer(state = initialState, action) {
  switch (action.type) {
    case "DO_THIS":
      return {
        ...state,
        users: action.payload,
      };
    default:
      return state;
  }
}
```

In `/src/reducer/`, create an index.js file within Reducer folder to combine all reducers. Redux provides us with a combineReducer function for combining all reducers in the app.
	- const reducer = combineReducer({});

In `/src/reducer/TestReducer.js`,
```
import { combineReducers } from "redux";
import TestReducer from "./TestReducer";

const reducers = combineReducers({
  Test: TestReducer,
  //other reducers come here...
});

export default reducers;

```

In `/src/store/index.js`, create a store for all reducers created.
```
import { applyMiddleware, createStore } from "redux";
import thunk from "redux-thunk";
import reducers from "./Reducers";

//thunk middleware is used to intercept actions so as to make API call before dispatching result to reducer
const store = createStore(reducers, applyMiddleware(thunk));

export default store;
```

Finally, 
In `Index.js`, Provide the store to the application globally
```
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store";

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

```

The Store file structure should look like

![store file structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7e512rjq59xn8c3krif7.PNG)

### To bring it all together
In `App.js`,
* import `useDispatch` hook, to dispatch action that'll get fetch users from a remote server
* dispatch that action on component mount, 

`/src/App.js`
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5m36nczm68jndki4v5ee.PNG)

In `src/components/Users.js`,
* Access data in TestReducer using `useSelector` hook
* Map through data to display list of users

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6icajprq5w5gyp52mrt5.PNG)

# Resulting View
![View](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yu8yjvo8rsxn5e4ct8sq.PNG)

--

_Note: There are several ways to structure this, this is just a fairly simple way to get up and running quickly. I hope this help you get started quickly._ :)