Skip to content

Instantly share code, notes, and snippets.

@iocat
Last active November 23, 2020 04:03
Show Gist options
  • Save iocat/40d8eaae82c1a86b0c0fd91223542a5f to your computer and use it in GitHub Desktop.
Save iocat/40d8eaae82c1a86b0c0fd91223542a5f to your computer and use it in GitHub Desktop.
State Management without Redux but with useReducer/useContext.
// Reproduced in TSX from blog :P https://blog.logrocket.com/use-hooks-and-context-not-react-and-redux/
export type ExampleAction1 = {
type: 'ACTION'
}
export type ExampleAction2 = {
type: 'ACTION2'
}
export type Action = ExampleAction1 | ExampleAction2;
export const reducer = (reducerState?: ReducerState, action?: Action): ReducerState => {
if (action == undefined || reducerState == undefined) {
return { state: {}, dispatcher: () => { } }
}
switch (action.type) {
case 'ACTION':
return reducerState
case 'ACTION2':
return reducerState
default:
const _exhaustive: never = action
}
return reducerState
}
type GlobalState = {
state: ReducerState,
dispatcher: Dispatcher
}
export const GlobalStateContext: Context<GlobalState> = createContext<GlobalState>({ state: {}, dispatcher: () => { } });
export const GlobalStateContextProvider = ({ children }: { children: ComponentChildren }) => {
const [state, dispatcher] = useReducer<ReducerState, Action>(reducer, reducer())
const value: GlobalState = { state, dispatcher }
return <GlobalStateContext.Provider value={{ state, dispatcher }}>
{children}
</GlobalStateContext.Provider>
}
import {GlobalStateContext, GlobalState} from 'index.tsx'
export const MyElement = () => {
const {state, dispatcher} = useContext<GlobalState>(GlobalStateContext);
return <>
{state.blah}
</>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment