Skip to content

Instantly share code, notes, and snippets.

@SMWARREN
Created January 26, 2023 23:34
Show Gist options
  • Save SMWARREN/b798aa4753c92860810f2db0f4f3f380 to your computer and use it in GitHub Desktop.
Save SMWARREN/b798aa4753c92860810f2db0f4f3f380 to your computer and use it in GitHub Desktop.
Better State Management Then Redux Context
// store.js
import React, {createContext, useReducer} from 'react';
const initialState = {};
const store = createContext(initialState);
const { Provider } = store;
const StateProvider = ( { children } ) => {
const [state, dispatch] = useReducer((state, action) => {
switch(action.type) {
case 'action description':
const newState = // do something with the action
return newState;
default:
throw new Error();
};
}, initialState);
return <Provider value={{ state, dispatch }}>{children}</Provider>;
};
export { store, StateProvider }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment