Skip to content

Instantly share code, notes, and snippets.

@chengsokdara
Last active May 11, 2023 22:25
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chengsokdara/1535c912fa18fbb882cb9d74f7760f85 to your computer and use it in GitHub Desktop.
Save chengsokdara/1535c912fa18fbb882cb9d74f7760f85 to your computer and use it in GitHub Desktop.
React global state in 15 lines of code.
// Author: Sokdara Cheng
// Contact me for web or mobile app development using React or React Native
// https://chengsokdara.github.io
import React, { createContext, useContext, useReducer } from "react";
import initialState from "./initialState"; // object of initial states
import reducer from "./reducer"; // https://reactjs.org/docs/hooks-reference.html#usereducer
const Store = createContext({
dispatch: () => null,
state: initialState,
});
const StoreProvider = ({ 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: 'TEST_ACTION', payload: { test: 'new value' } })
*
*
* // initialState.js
* export default {
* test: "test",
* };
*
* // reducer.js
* export default (state, action) => {
* switch (action.type) {
* case "TEST_ACTION":
* return {
* ...state,
* ...action.payload,
* };
* default:
* return state;
* }
* };
*/
@AshleyAitken
Copy link

Thanks for sharing. What are the disadvantages of this approach to global state, if any? Scaling? Complexity? Does all GobbaK state go here or is it a good idea to create a number of different StoreProviders? How does this compare (briefly) with Redux and MobX. Sorry for all the questions?

@chengsokdara
Copy link
Author

@AshleyAitken

  • I would say it has all the pitfalls of Context API other than that it is much simple than Redux or MobX for small projects.
  • For big projects, it's still Redux or MobX.
  • Only need one of this to manage all global states.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment