Last active
January 31, 2022 01:50
-
-
Save spacerumsfeld-code/89f3352fe6a4cfc747df31f8dab980df to your computer and use it in GitHub Desktop.
Redux Mini
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
/** 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