How to migrate from Redux to React Context API
Tags: react, redux, context, migrate
Published: 2020-02-26 04:41:22

---
title: How to migrate from Redux to React Context API
published: true
description: A guide on how to easily migrate from Redux to React Context API 
tags: react, redux, context, migrate
cover_image: https://images.unsplash.com/photo-1581276879432-15e50529f34b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60
---


### 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](https://codesandbox.io/s/react-redux-example-qzoro) 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.

```js

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

``` 

### 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.  

{% gist https://gist.github.com/csantiago132/2548f517b9e6f8f56b6b841b0ca89559 
%}


### 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. 

{% gist https://gist.github.com/csantiago132/0d2bc0b5e18fce613d70a6232f5ca42e/35e1d961d49b9280fa34f327451efa27988d0bef 
%}


#### 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()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) gives us an array of key-value pairs from the `reducers` object passed as a parameter. 

{% gist https://gist.github.com/csantiago132/0d2bc0b5e18fce613d70a6232f5ca42e/ff811b78ccd5640f6d68f3fbd6c7a036f97598c8 
%}


#### 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**](https://reactjs.org/docs/hooks-reference.html#usereducer) later on. 

{% gist https://gist.github.com/csantiago132/0d2bc0b5e18fce613d70a6232f5ca42e/9605668627765e4c36f6a2d0c4946b02f0da6154 
%}


#### 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.

{% gist https://gist.github.com/csantiago132/0d2bc0b5e18fce613d70a6232f5ca42e/427e7861cb511780f1248a20ba6caa01f5420661 
%}


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

{% gist https://gist.github.com/csantiago132/0d2bc0b5e18fce613d70a6232f5ca42e/1fbb96147a0a8bb85ed59a380dc4af85e92b4ed5 
%}


#### 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. 

{% gist https://gist.github.com/csantiago132/0d2bc0b5e18fce613d70a6232f5ca42e/586f4bccbc8bca8c0df0d5fae73ff2707e1ae3d1 
%}


### 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. 

{% gist https://gist.github.com/csantiago132/e1634d440708ee5fbbb05e4bba63180c/e2b4a445906cf5953629c0d7636673fe2adbe549 
%}


#### 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.

{% gist
https://gist.github.com/csantiago132/e1634d440708ee5fbbb05e4bba63180c/ce2fbbfe62c3a6248b1b7115831396972e86c568 
%}


#### 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

{% gist
https://gist.github.com/csantiago132/e1634d440708ee5fbbb05e4bba63180c/2e9a70a2ab1e8f01eda3e16ab4c568656c000b36 
%}


#### 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. 

{% gist 
https://gist.github.com/csantiago132/e1634d440708ee5fbbb05e4bba63180c/b58c0e4f68bf5b54476590eaab5d5c0cd0c48313
%}


### 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 

{% gist 
https://gist.github.com/csantiago132/d0269a753bb2b168b6b673c0b4cb9ccc/883b01abaf21ec3322f998333c943ecdc58c41c1
%}


#### 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 `mapStateToProps`function.

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. 

{% gist 
https://gist.github.com/csantiago132/d0269a753bb2b168b6b673c0b4cb9ccc
%}


### 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:

{% gist
https://gist.github.com/csantiago132/5445aadcdb62ae4e74d17f9339d3f8b2
%}


##### 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.

{% gist
https://gist.github.com/csantiago132/03fa70f9fd22803637bd9c9965bd29c3
%}

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**
{% codesandbox x4683  module=%2Fsrc%2Fprovider%2Fconnect.js %}


### 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**
- [Using Context API in React (Hooks and Classes)](https://www.taniarascia.com/using-context-api-in-react/) by [Tania Rascia](https://twitter.com/taniarascia). 
- [A Beginner’s Guide to Currying in Functional JavaScript] (https://www.sitepoint.com/currying-in-functional-javascript/) by [M. David Green](https://www.sitepoint.com/author/mdavidgreen/).

**CodeSanbox** 
- [Initial CodeSandbox using Redux](https://codesandbox.io/s/react-redux-example-qzoro)
- [Final CodeSandbox using React Context API](https://codesandbox.io/s/react-context-provider-example-x4683).

**Github Repo** 
{% github 
https://github.com/csantiago132/migrate-from-redux-to-react-context-provider 
no-readme
%}