Add Redux to an Existing React Application

InstructorJamund Ferguson

Share this video with your friends

Send Tweet

This lesson shows you how to install redux and react-redux to create a redux store and then use the Provider component to enable redux throughout your entire application.

First we start by installing redux and react-redux using: yarn add redux react-redux

Then we use the createStore method in redux to keep a place to store our data.

import { createStore } from "redux";

export const store = createStore(reducer);

After that we create a reducer function. Reducer functions are similar to the Array prototype's reduce method.

The first argument could be considered the previous state of the world and the second argument is the current action being applied.

function reducer(state, action) {
	return state;
}

Reducers absolutely must not have side effects and should never change the previous state. Instead in reducers it's common to see the pattern of using object spread syntax to make a copy of the current state into a new object, before modifying any properties:

return  { ...state, changedProperty: "value" }

Once a redux store is created we use the <Provider> component to pass that store down to each component. More info about Provider can be found here: https://react-redux.js.org/api/provider