3 steps to create custom state management library with React Hooks and Context API
Tags: react, reactnative, redux, javascript
Published: 2022-03-15 05:46:51

![3 steps to create custom state management library with React Hooks and Context API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhvapr806pcaojr55x02.png "3 steps to create custom state management library with React Hooks and Context API")
 In this article, I will introduce the React Context API for state management and create a similar solution as Redux without using a third-party library.

**React Context API**
It’s actually not a new idea. Context API as part of React for a long time, but only in an experimental state.

Since React 16.3.0 it’s officially stable and ready to use in production.


### Without further ado, here are the steps

**Step: 1** Creating Provider and connect function (same as react-redux connect and Provider) using useReducer, createContext & useContext

```javascript
import React, { useReducer, createContext, useContext } from "react";
const initialState = {};
// Create App Context
export const Context = createContext(initialState);
export const Provider = ({ children, reducers}) => {
    const defaultState = reducers(undefined, initialState);
    if (defaultState === undefined) {
       throw new Error("reducer's should not return undefined");
    }
    const [state, dispatch] = useReducer((_state, _action) => {
        return reducers(_state, _action);
    }, defaultState);
    return (
        <Context.Provider value={{ state, dispatch }}>
            {children}
        </Context.Provider>
    );
};
export const useDispatch = () => useContext(Context).dispatch;
export const useSelector = (callback) => {
  const state = { ...useContext(Context).state };
  return callback ? callback(state) : state;
};
```

**Step: 2** Connect react app to above created Provider

```javascript
const actionMap = {
  INCREMENT: (state, action) => ({ ...state, count: state.count + 1 }),
  DECREMENT: (state, action) => ({ ...state, count: state.count - 1 }),
};

const countReducer = (state = { count: 0 }, action) => {
    const exec = actionMap[action.type];
    return exec ? exec(state, action) : state;
};


const reducers = { countReducer };
const App = () => (
    <Provider reducers={reducers}>
        <Component />
    </Provider>
);
```

**Step: 3** Connect component to react Context

```javascript
const Component = () => {
  const dispatch = useDispatch();
  const { count } = useSelector((state) => state.countReducer);
  return (<h3>Context State: {count} </h3>)
}
```

![3 steps to create custom state management library with React Hooks and Context API](https://media3.giphy.com/media/py2UYwTIX5SXm/giphy.gif?cid=ecf05e470fn2sfrohfn3linr9dax8ktqwbcx4wmn5rhq2x7o&rid=giphy.gif&ct=g "3 steps to create custom state management library with React Hooks and Context API")



> Live Demo: [Here](https://stackblitz.com/edit/reactjs-usecontext-usereducer-state-management)

___


![3 steps to create custom state management library with React Hooks and Context API](https://media.giphy.com/media/20KLYSIhq35V4EpVlC/giphy.gif "3 steps to create custom state management library with React Hooks and Context API")


> Bonus Tip 

```javascript
export const combineReducers = (reducers) => {
  const entries = Object.entries(reducers);
  return (state = {}, action) => {
    return entries.reduce((_state, [key, reducer]) => {
      _state[key] = reducer(state[key], action);
      return _state;
    }, {});
  };
};
```

Got any questions or additional? please leave a comment.

---

### What is Next 
{% link https://dev.to/devsmitra/react-best-practices-and-patterns-to-reduce-code-2bff %}
{% link https://dev.to/devsmitra/how-to-solve-rest-api-routing-problem-with-decorators-5b3n %}

{% user devsmitra %}

###### Catch me on
<p>
{% cta https://www.youtube.com/@bit-buddy?sub_confirmation=1 %} Youtube {% endcta %}
{% cta https://github.com/devsmitra %} Github {% endcta %}
{% cta https://www.linkedin.com/in/rahul-sharma-18b8b374 %} LinkedIn {% endcta %}
{% cta https://devsmitra.medium.com %} Medium {% endcta %}
{% cta https://stackblitz.com/@devsmitra %} Stackblitz {% endcta %} {% cta https://devsmitra.hashnode.dev %} Hashnode {% endcta %}
{% cta https://hackernoon.com/u/devsmitra %} HackerNoon {% endcta %}
</p>