Setting Up Redux for Your React App

Saurav Aggarwal
The Startup
Published in
4 min readSep 26, 2020

--

What is Redux?

Okay, so this is the first question that has to be answered when you are considering redux for your app. So redux is a state(data that your application needs) management library. Basically react is used when you need to share some data throughout the application and if your application follows the flux architecture (in which data flows only in one flow normally from parent to child in most applications). So why would you be considering this? well, there are many reasons. Some of those can be as follows:

  1. You want some data to be shared your application which is on the same levels or not on the same level. The Most Common Used case is logging in your user. Suppose you have a component and you want that when user logins it should change the navbar behavior.
  2. You are fed up using callbacks to trigger a change in some components.
  3. You see how having state management can make managing your application more manageable.

so above are some reasons why I use redux in my projects but you might have some other reason. There are endless cases in which redux can be useful in react.

Redux terms you should know

  1. Store: First-term that you will hear once you get into redux and frankly it’s nothing more than a fancy way of having a local DB that is accessible to your application. And mainly the data which is shared by many components is present here.
  2. Reducer: Another Scary term that scares the hell out of me till now but it’s not more than the SQL for your store. In reducer you write the query that will mutate your store like in a DB you will use some queries to mutate the DB here you will use reducers to mutate your store.
  3. Dispatcher: This is a tricky one to explain but I’ll try. You write a SQL query for your DB but how will you execute it you need some SQL console to execute it right? The dispatcher does the same thing it executes the reducer to your store.

Okay, that are all the terms you need for implementing and understanding redux.

So in summary DISPATCHER triggers a REDUCER that mutates the STORE.

Okay enough talking let’s code.

REACT AND REDUX

Okay, so we’ll tackle this problem step by step.

  1. Make A Store.
  2. Make A Reducer.
  3. Make A dispatcher.

Note: For installation of redux and react-redux run below command

npm i redux react-redux
yarn add redux react-redux

Making a Store

Frankly speaking, it’s the easiest part of the whole process.

//index.js//imports
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducer from './reducers/file-having-reducer';
//store
let store = createStore(reducer);
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
rootElement);

Making a Reducer

Now let’s make a reducer. Ok, so what is a reducer? reducer is nothing it’s just like a function that takes 2 arguments state and action. State argument is taken care of by redux and we don’t have to do anything regarding that but action is an object that is sent by us which has two things one is the type and the other is the payload. The type will define the case which will run in switch and payload is the data that you may want to give for manipulation of state. When a particular case had run you should return a newly updated state.

//structure of action
action = {
type:'ANY_ACTION_DUE_TO_WHICH_IT_WILL_RUN_PARTICULAR_ACTION',
payload:{
data:data
}
}
//file-containing-reducer
const initialState = 0;
function reducer(state=initialState,action){
switch(action.type){
case 'ADD' : return state + 1;
case 'SUBTRACT' : return state - 1;
case 'UPDATE' : return action.payload;
default : return state;
}
}
export default reducer;

Making A Dispatcher

Okay, this part is a little difficult so just bear with me.

//dispatcher.js
export const addToState = () => ({ type: 'ADD' });
export const subtractFromProps = () => ({ type: 'SUBTRACT' });export const update = (data) => ({ type: 'UPDATE', payload: data });

Above are dispatcher these are nothing just function returning some objects

Now we are ready to integrate redux in our application.

So for connecting our store and our dispatcher to themselves we have to use connect that we will import from react-redux. Now, what will connect do it will take 2 functions as arguments the first function will map store data to props and the second will map dispatch, and then it will return us a function to which we’ll give our component i.e. App as an argument and the rest will be taken care by redux.

//App.js
import React from "react";
import { connect } from "react-redux";
import {
addToState,
subtractFromState,
update
} from "./dispatchers/dispatcher";
import "./styles.css";
function App(props) {
return (
<div className="App">
<h1>Count : {props.count}</h1>
<button onClick={() => props.add()}>ADD</button>
<button onClick={() => props.update(Math.random())}>UPDATE</button>
<button onClick={() => props.subtract()}>SUBTRACT</button>
</div>);
}
const mapStateToProps = (state) => {
return {
count: state
};
};
const mapDispatchToProps = (dispatch) => {
return {
add: () => dispatch(addToState()),
update: (data) => dispatch(update(data)),
subtract: () => dispatch(subtractFromState())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);

And we are done. And in the same way, we can attach dispatchers and store data to other components.

I won’t lie you won’t get it the first time you will have to play around to get it but once you get it there’s no way you will be back to using state only.

Below is the working example:

Below is more of a complex example and will help you to understand more about how the redux can be more of use

NOTE: There will be some issues you will encounter when working with objects in the store. That of components not updating on state change that is because changes will only be triggered if react finds a different object so whenever we return state from reducer we return a whole new object in order to counter this problem. If you still want more clarification go on youtube or ping me on LinkedIn. I’ll be more than happy to help.

--

--

Saurav Aggarwal
The Startup

Just a curious dev who writes when gets bored of work life