This is a pattern I found myself re-writing a bunch so I decided to drop myself a note, hopefully it helps you out!
Last active
August 30, 2021 16:49
-
-
Save anglinb/49223e9996655cf07e2a24eadbd2421d to your computer and use it in GitHub Desktop.
Boilerplate for a context & reducer, basically mini redux
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
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> | |
); | |
}; |
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
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