DEV Community

Cover image for How to migrate from Redux to React Context API
Carlos Santiago
Carlos Santiago

Posted on • Edited on

How to migrate from Redux to React Context API

Introduction

The main goal of this article is to replace Redux with React Context API. We will achieve this by going to any connected component and replace a line of code with a connect function that we will write.

When you finish reading this article, you'll be able to migrate from Redux to React Context API smoothly, quicker, and without rewriting plenty of code. We will achieve our goal doing these five steps:

  • Step 1: Model your reducers in an object
  • Step 2: Create the combineReducer function
  • Step 3: Create the app's provider
  • Step 4: Create the connect function
  • Step 5: Connect the components to the provider

Prerequisites

You will need some knowledge in React, Redux and React Context API. Also, some knowledge of Higher Order Functions and currying functions in javascript would be helpful.

Before we start...

If you want to do this tutorial while you read, you can open this CodeSandbox using React and Redux in a new tab, fork it and start coding. The CodeSandbox is embedded at the end of the article for easy reference.

Folder Structure

Let's create the folder structure where we are going to place the code. This structure is a suggestion and should not dictate how you organize your code.


directory
  └─── src
   |   | ... other-directories
   |   |─── provider
   |        |   provider.js
   |        |   connect.js
   |        |   reducers.js
   |   |─── utils
   |        |   combineReducers.js
   |   | ... other-directories

Enter fullscreen mode Exit fullscreen mode

Step 1: Model your reducers

Go to reducers.js and start placing all the reducers of the app with it's key inside an object.

Step 2: Start writing the combineReducer function

First, let's start writing the function that will create the root reducer and the parameters it needs.

2.1 • Start modeling the initial global state

In this iteration, we will call each reducer to get its initial state. Pass undefined as the state parameter and anything you want as the action parameter, each reducer will return the initial state provided. Then, the results are added to the globalState variable.

Object.entries() gives us an array of key-value pairs from the reducers object passed as a parameter.

2.2 • Start writing the global reducer function

Now, we are going to write the primary reducer function. We are writing this function to pass it to the useReducer hook later on.

2.3 • Let’s update the global state

The most important part of this function is to get the next state. We are going to iterate through each reducer available and pass the action parameter to get the next state returned by the reducer.

In the iteration, we are going to compare the returned object with the current state. If these objects are not the same, it means there was an update, and we are going to replace the state with the updated object.

Next, if the state has changed, we will return the updated state. If not, we return the previous state.

2.4 • Finish writing the function

Finally, we will return an array with the initial state and the global reducer function. These values will be passed to the useReducer hook.

Step 3: Write the app's Provider

Let's write the app's provider. Then, import the object containing our reducers and the combineReducer function from the previous step.

3.1 • Wrap up the function in the useCallback hook

We are not expecting our initial state, or the objects containing the reducers, to change on each re-render. So, let's optimize our function by using the useCallback hook.

useCallback will return a memoized version of the callback that only changes if one of the inputs has changed. There is no need for this function to run on every re-render.

3.2 • Setup the rest of the provider

Next, let's wrap up the provider by doing a few more steps. First,
destructure the returned value of the useCallback function and set up the useReducer hook.

Once that's done, create a useMemo hook to wrap the returned value of the useReducer hook. Why useMemo? Since this is the global provider, there are two main reasons:

  • Your context value changes frequently
  • Your context has many consumers

3.3 • Finish up the app's provider

Finally, let's return the consumer and export the provider and have it ready to pass context to all the children below it.

Step 4: Start writing the connect function

The HOC function is the last function we will write before we start connecting the component to the provider.

This function will pass the state and the global reducer to each component. This "connects" to React Context Provider API and lets our components consume the values given by it.

The simplest use case of our function is a purely curried one and will take three parameters:

  • mapStateToProps - required
  • mapDispatchToProps - optional - not all components dispatch actions
  • Component - required

4.2 • Return a connected component

Let's place the Context.Consumer to have access to the global state and dispatch function. Then, let's pass value.state to the mapStateToPropsfunction.

Remember, the mapDispatchToProps parameter is optional. If you pass this parameter, pass value.dispatch to the mapDispatchToProps function.

Finally, let's combine all props and add the final result to the component. Now this component is connected to the React Context API.

Step 5: The last step: connect our components

Now we can migrate from Redux to React Context Provider API quickly and with little refactoring on our part.

Replace the Redux Provider

Let's start by replacing the Provider from Redux with the one we created. Your main app file should look like below:

Replace the Redux connect function

Finally, let's replace the connect function imported from Redux with our connect function. Your component should look like below.

You can access all the properties returned from mapStateToProps and mapDispatchToProps as props inside the connected component.

Lastly, refresh the page and the app should be connected to the React Context API. Repeat this step to all the components that you want to replace Redux with React Context Provider API.

Here is a CodeSandbox with all the code we wrote and connected to React Context API

Conclusion

So there you have it, in five steps, we successfully moved away from Redux and replace it with React Context API.

  • Model your reducers in an object
  • Create the combineReducer function
  • Create the app's provider
  • Create the useConnect function
  • Connect the components to the provider

Resources

Articles

CodeSanbox

Github Repo

Top comments (4)

Collapse
 
heymanish profile image
Manish

Thanks for this article. This is really helpful.

Collapse
 
csantiago132 profile image
Carlos Santiago

thank you so much! I hope everything is clear and well explained :)

Collapse
 
heymanish profile image
Manish

Yes. I don't know redux however I have a project with redux and I need to convert it to context API but I am stuck on actions and dispatchers I don't know how I will call dispatchers from components. :(

Thread Thread
 
csantiago132 profile image
Carlos Santiago

From context or from redux? Sorry for the late reply, I needed to disconnect from development outside of work for a few months and recharge