DEV Community

Nirmal Thomas Mathew
Nirmal Thomas Mathew

Posted on

Create your own React State Management

Level: Intermediate⚛️; Scroll to bottom for full code⬇️

Pen and Paper

The implementation is simple, I think many blogs have been written about the same method; I think this needed to be written. We will be using react context for universal state management.

  • Create a wrapper component
  • use React.createContext to create state context
  • create new app state using useReducer()
  • create a method in reducer function to add / update state

Implementation

Create wrapper

export const StateManager = ({children}) => {
    return (

    )
}
Enter fullscreen mode Exit fullscreen mode

Creating context

export const store = React.createContext({})
Enter fullscreen mode Exit fullscreen mode

Creating state in wrapper

// store context
export const store = React.createContext({})
const {Provider} = store

export const StateManager = ({children}) => {
    // creating state
    const [state, dispatch] = React.useReducer(reducer, {})
    return (
        <Provider value={{state, dispatch}}>
            {children}
        </Provider>
    )
}
Enter fullscreen mode Exit fullscreen mode

Implementing reducer

const reducer = (state, action) => {
    const {type, payload} = action
    switch (type){
        case "ADD":
            return {...state, ...payload}
        default:
            return state;
    }
}
Enter fullscreen mode Exit fullscreen mode

One thing to be noted is that, the payload given must be an object containing app data

Usage

import {useContext} from "react"
import {store, StateManager} from "./StateManager.js"

function App(){
    return (
        <StateManager><ChildComp /></StateManager>
    )
}

function ChildComp(){
    const {state, dispatch} = useContext(store)
    // work with app state

    return (
        <div></div>
    )
}
Enter fullscreen mode Exit fullscreen mode

References

How to use useReducer ?
How to use react context ?

Whole Code

// StateManager.js
import React from "react"
// reducer function 
const reducer = (state, action) => {
    const {type, payload} = action
    switch (type){
        case "ADD":
            return {...state, ...payload}
        default:
            return state;
    }
}
// store context
export const store = React.createContext({})
const {Provider} = store

export const StateManager = ({children}) => {
    // creating state
    const [state, dispatch] = React.useReducer(reducer, {})
    return (
        <Provider value={{state, dispatch}}>
            {children}
        </Provider>
    )
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)