Skip to content

Instantly share code, notes, and snippets.

@chengsokdara
Created October 15, 2020 01:01
Show Gist options
  • Save chengsokdara/93cf0718cec48f286cbf5706c19fb5e3 to your computer and use it in GitHub Desktop.
Save chengsokdara/93cf0718cec48f286cbf5706c19fb5e3 to your computer and use it in GitHub Desktop.
React global state in 15 line of codes, TypeScript version.
// Author: Mr. Cheng Sokdara
import React, {
Dispatch,
FC,
createContext,
useContext,
useReducer,
} from "react";
import initialState, { StoreState } from "./initialState";
import reducer, { StoreAction } from "./reducer";
export type StoreContext = {
dispatch: Dispatch<StoreAction>;
state: StoreState;
};
const Store = createContext<StoreContext>({
dispatch: () => null,
state: initialState,
});
const StoreProvider: FC = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<Store.Provider value={{ dispatch, state }}>{children}</Store.Provider>
);
};
export const useStore = () => useContext(Store);
export default StoreProvider;
/*
* How To Use:
* - wrap root App component with StoreProvider
* <StoreProvider><App><StoreProvider>
*
* - call useStore to get state and dispatch
* const { state, dispatch } = useStore()
*
* - change state by passing action to dispatch
* dispatch({ type: 'ACTION', payload: { test: 'new value' } })
*/
// initialState.ts
export type StoreState = {
test: string;
};
export default {
test: "test",
};
// reducer.ts
import { StoreState } from './initialState'
export type StoreAction = {
type: "TEST_ACTION";
payload: any;
};
export default (state: StoreState, action: StoreAction) => {
switch (action.type) {
case "TEST_ACTION":
return {
...state,
...action.payload,
};
default:
return state;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment