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 (
)
}
Creating context
export const store = React.createContext({})
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>
)
}
Implementing reducer
const reducer = (state, action) => {
const {type, payload} = action
switch (type){
case "ADD":
return {...state, ...payload}
default:
return state;
}
}
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>
)
}
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>
)
}
Top comments (0)