Skip to content

Instantly share code, notes, and snippets.

@sakilahmmad71
Last active March 3, 2022 05:24
Show Gist options
  • Save sakilahmmad71/df0426f2db0d0fc37916c0593ed86940 to your computer and use it in GitHub Desktop.
Save sakilahmmad71/df0426f2db0d0fc37916c0593ed86940 to your computer and use it in GitHub Desktop.
import { createContext, useContext, useReducer } from 'react';
const MyContext = createContext();
myContext.displayName = 'MyContext';
const MyContextProvider = ({ initialState = {}, ...props }) => {
const [state, dispatch] = useReducer(
(state, action) => {
switch (action?.type) {
case 'MYTYPE' : {
return {...state, name : action?.payload }
}
default : {
throw new Error(`Unhandled action type: ${action.type}`)
}
}
},
{ initialState }
);
const value = [state, dispatch];
return <MyContext.Provider value={value} {...props} />
}
const useMyContext = () => {
const context = useContext(MyContext);
if (context === undefined) {
throw new Error(`useMyContext must be used within a MyContextProvider`)
}
return context;
}
const myAction = dispatch => dispatch({ type : "MYTYPE" });
const myAnotherAction = (dispatch, payload) => dispatch({ type : "MYANOTHERTYPE", data: payload });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment