Skip to content

Instantly share code, notes, and snippets.

@anglinb
Last active August 30, 2021 16:49
Show Gist options
  • Save anglinb/49223e9996655cf07e2a24eadbd2421d to your computer and use it in GitHub Desktop.
Save anglinb/49223e9996655cf07e2a24eadbd2421d to your computer and use it in GitHub Desktop.
Boilerplate for a context & reducer, basically mini redux

Mini-redux, w/ Vanilla React 🎉

This is a pattern I found myself re-writing a bunch so I decided to drop myself a note, hopefully it helps you out!

import { createContext, FC, useReducer } from 'react';
/**
* Context hook
*
*/
type ExampleContextType = {
value: string ,
updateValue: (newValue: string) => void
};
// Some reasonable defaults we can return if we don't have things loaded
const defaultContext: ExampleContextType = {
value: '',
updateValue: () => {},
};
/**
* Reducer
*
*/
// Reducuer store type
type ExampleContextStoreType = {
value: string
}
export enum ActionKind {
Set
};
export type SetAction = {
kind: ActionKind.Set
value: string
};
type Action =
| SetAction
const reducer = (state: ExampleContextStoreType, action: Action): ExampleContextStoreType => {
switch(action.kind) {
case(ActionKind.Set): {
const { value } = action;
return {
...state,
value
}
}
}
}
export const ExampleContext = createContext<ExampleContextType>(defaultContext);
export const ExampleProvider: FC = ({ children }) => {
const [store, dispatch] = useReducer(reducer, {
value: ''
});
return (
<ExampleContext.Provider
value={{
value: store.value,
updateValue: (value) => {
dispatch({
kind: ActionKind.Set,
value,
})
}
}}
>
{children}
</ExampleContext.Provider>
);
};
import { useContext } from 'react';
const SomeComponent = () => {
const {
updateValue,
value
} = useContext(ExampleContext);
return (
<input type="text" value={value} onChange={(e) => {
updateValue(e.target.value)
}} />
)
};
export const App = () => {
return (
<ExampleProvider>
<SomeComponent />
</ExampleProvider>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment