Last active
December 19, 2021 19:27
-
-
Save rsispal/b8ea0736d9ecd22797d528a39fd65dc3 to your computer and use it in GitHub Desktop.
[TEMPLATE] React Context/Reducer/Hook State Management (Redux Alternative)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createContext, useReducer, useContext, FC, useEffect, useMemo } from "react"; | |
type InnerState = {}; | |
export interface TemplateContextProviderState {} | |
export interface Action { | |
type: ActionType; | |
payload: {}; | |
} | |
export enum ActionType { | |
NO_ACTION, | |
} | |
const reducer = (state: InnerState, action: Action) => { | |
console.log("TemplateContextProvider :: DISPATCH - action", ActionType[action.type]); | |
switch (action.type) { | |
case ActionType.NO_ACTION: | |
default: { | |
return { | |
...state, | |
}; | |
} | |
} | |
}; | |
const initialState: InnerState = {}; | |
const TemplateContext = createContext(initialState as TemplateContextProviderState); | |
export const useTemplateContext = () => { | |
const context = useContext<TemplateContextProviderState>(TemplateContext); | |
if (!context) { | |
throw new Error("useTemplateContext must be used within a TemplateContextProvider"); | |
} | |
return context; | |
}; | |
export const TemplateContextProvider: FC = ({ children }) => { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
const value: TemplateContextProviderState = useMemo( | |
() => ({ | |
...state, | |
}), | |
[state] | |
); | |
return <TemplateContext.Provider value={value}>{children}</TemplateContext.Provider>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment