Last active
November 23, 2020 04:03
-
-
Save iocat/40d8eaae82c1a86b0c0fd91223542a5f to your computer and use it in GitHub Desktop.
State Management without Redux but with useReducer/useContext.
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
// 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> | |
} |
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 {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