Guide on How to Properly Use and Structure Redux in Your React App with an Example
State management in most modern front-end framework particularly in ReactJs is hard and that is where Redux comes to save us. However, if your app isn't structured properly, Redux will bring you more complexities and make your whole codebase more difficult to understand, navigate and scale.
Below is a comprehensive guide on how to properly use and structure your redux in your react app:
A. Install necessary dependencies:
// You can also use yarn add
// I encourage you to check out their documentations on why we use them
npm install redux redux-devtools-extension redux-thunk react-redux axios
B. Create store.js
file in the src
folder of your react app:
C. Setup your store.js
:
import { createStore, combineReducers, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
const reducer = combineReducers({})
const initialState = {};
const middleware = [thunk];
const store = createStore(
reducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;
D. Wrap your index.js
file with a provider and pass in the store:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
E. Create constants
folder in the src, some files such as userConstants.js
and add the constants
:
F. Create reducer
folder in the src, some files such as userReducers.js
and add the reducers
:
G. Create action
folder in the src, some files such as userActions.js
and add the actions
:
H. Combine the reducers in the store.js
:
I. Use your reducers
in any desired React Component e.g Register.js
:
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
// Register action
import { register } from "../actions/userActions";
const Register = ({ history, location }) => {
const dispatch = useDispatch();
// This is what you use to get the values in registerReducer.
// You can also do this with any other reducer or component
const { loading, error,success, serverResponse } = useSelector((state) => state.userRegister);
const handleSubmit = (e) => {
e.preventDefault();
dispatch( register (name, email, username, password));
}
// Rest of the app
}
Congratulations! You made it!
Please leave a comment, follow me on twitter Bonaventure Chukwudi
Please Be my patreon ❤