In this article, we will learn about using Redux with React. We won’t engage much into theory and quickly set it up. This is a reference guide to get you started with Redux in your projects.

Installing Redux

Of course, the first step is to install Redux and React-redux libraries in your project –

npm install react react-redux

Or, you can use yarn –

yarn add react react-redux

Main Components

To work with Redux, we need to understand 4 components –

  1. Store
  2. Reducer
  3. Provider
  4. Hooks – useSelector() and useDispatch()

Before moving forward, first do these tasks –

  • Create a folder in src with name reducers.
  • Also create a file in src again, with name store.js.
Redux store and reducers

Redux Store

Store is the central file which connects all the dots of redux. It has defined format and for all simple use cases, it remains same. So, just copy this code into your store.js

import {createStore} from 'redux';
import rootReducer from './reducers/index';

const store = createStore(rootReducer);

export default store;

Reducers

Reducers are the central state management functions where we perform updates in states. You can create single reducer file and put all the functions there or you can create multiple files for better management. We will discuss about multiple files in this article.

Let’s create our first reducer file – firstReducer.js in reducers folder.

const initialState = {
    isLogin : 0,
}

const reducer = (state = initialState, action) => {
    if(action.type === 'CHANGE_LOGIN'){
        return {
            ...state,
            isLogin: action.payload.isLogin
        }
    }

    return state;
}
export default reducer;

We created this reducer for a specific purpose. It will be used to check if user is logged in or not. Since the state isLogin will be available throughout the application, so we can get the login status on any page of our project.

  • initialState – A default state value.
  • action – Object which holds information about an action. For example, suppose you want to use redux for operations like login, increasing / decreasing count on page views, keeping user’s name etc. In order to differentiate between all these operations we need some criteria. action is used for that. It has two properties –
    • type – A string identifier for an operation. Like INCREASE_COUNT, DECREASE_COUNT, CHANGE_LOGIN, CHANGE_USER_NAME etc. You can name them whatever you want. Keep them meaningful for your own understanding.
    • payload – Payload holds the data to update in the state. So, suppose, User is logged in and now I want to change the state of isLogin to 1, then I will send the payload value to be 1. It can hold strings, numbers, array, object etc.

In this reducer we used action.type = 'CHANGE_LOGIN' and action.payload is an object {isLogin: 0 or 1}.

In the end, return state.

If you wish you can create more reducers. In our demo we will create more so you can refer from that.

Now you will need 1 more file which will combine all the created reducers. We will call it index.js

import { combineReducers } from 'redux';
import firstReducer from './firstReducer';
/**
* Import all the created reducers here
* like secondReducer, thirdReducer etc.
*/

const rootReducer = combineReducers({
    firstReducer,
    // List all your reducers
});

export default rootReducer;

This file combines all the reducers together. You just need to import them here.

Provider

Provider is just a Redux component which makes the store available throughout the application. So, you need to wrap the <App /> component in index.js with it –

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

You have to do 3 tasks –

  1. Import Provider component from react-redux.
  2. Import store from our store.js.
  3. Wrap <App /> in <Provider store={store}>

Now the redux is setup completely in the application. It’s time to use it.

React Hooks

There are two main hooks which we need to use.

useSelector()

This hook is called whenever there is a change in redux state. Doesn’t matter which state. It will be called. So, it acts as a subscriber function which keep tracks of state changes and inform components about it. Suppose user changed her name and 3 components are showing the name so it’s important for all the components to update it in their code. useSelector() will help in that. In our case we are keeping track of login, so –

import React from 'react';
import {useSelector} from 'react-redux';

export default function someComponent(props){
  const isLoggedIn = useSelector(
    state => state.firstReducer.isLogin
  )

  return(
    <p>User is loggedin? {isLoggedIn ? 'True' : 'False'}</p>
  )
}

Now when any state change, this hook will run but we will extract only the value we require. Here we require isLogin from firstReducer. So, we returned state.firstReducer.isLogin. If this value is not changed then there won’t be a re-rendering in this component otherwise it will. We know that state changed but isLogin isn’t, else some other state, so this component will not re-render.

useDispatch()

This hook is used to tell reducers that we want to change the state value. It’s quite simple to use.

import React from 'react'
import {useSelector, useDispatch} from 'react-redux'

export default function someComponent(props){
  const dispatch = useDispatch();
  const isLoggedIn = useSelector(
    state => state.firstReducer.isLogin
  )

  return (
    <button
      onClick={() => {
        dispatch({
          type: 'CHANGE_LOGIN',
          payload: {
            isLogin
: !isLoggedIn,
          },
        });
      }}
    >
      {isLoggedIn ? 'Logout' : 'Login'}
    </button>
  )
}

In the above code we are calling dispatch function on the click of button. Check that we are passing an object with keys type and payload. Recall that this is the action in reducer. This dispatch is saying that we want to run the function in reducers where condition is type='CHANGE_LOGIN'.

    Tweet this to help others

Live Demo

Live demo might not work in incognito / private window.

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles