Skip to content

Instantly share code, notes, and snippets.

@spacerumsfeld-code
Last active January 31, 2022 01:50
Show Gist options
  • Save spacerumsfeld-code/89f3352fe6a4cfc747df31f8dab980df to your computer and use it in GitHub Desktop.
Save spacerumsfeld-code/89f3352fe6a4cfc747df31f8dab980df to your computer and use it in GitHub Desktop.
Redux Mini
/** Redux Mini
Implementing a Redux-like global store with useContext and useReducer. Potentially useful in small-scale applications
where Redux is overkill.
(source: Next.js examples)
*/
/** Create the store and reducer to dispatch actions to it*/
import { useReducer, useContext, createContext } from 'react'
const CounterStateContext = createContext()
const CounterDispatchContext = createContext()
const reducer = (state, action) => {
switch (action.type) {
case 'INCREASE':
return state + 1
case 'DECREASE':
return state - 1
case 'INCREASE_BY':
return state + action.payload
default:
throw new Error(`Unknown action: ${action.type}`)
}
}
export const CounterProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, 0)
return (
<CounterDispatchContext.Provider value={dispatch}>
<CounterStateContext.Provider value={state}>
{children}
</CounterStateContext.Provider>
</CounterDispatchContext.Provider>
)
}
export const useCount = () => useContext(CounterStateContext)
export const useDispatchCount = () => useContext(CounterDispatchContext)
/** Wrap your application in the store */
<CounterProvider>
<Component {...pageProps} />
</CounterProvider>
/** You are now ready to access the store and dispatch actions to it! */
const RandomComponent = () => {
const count = useCount()
const dispatch = useDispatchCount()
const handleIncrease = (event) =>
dispatch({
type: 'INCREASE',
});
const handleDecrease = (event) =>
dispatch({
type: 'DECREASE',
});
return (
<button onClick={handleIncrease} />
...etc
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment