Skip to content

Instantly share code, notes, and snippets.

@spetroll
Created May 19, 2019 13:26
Show Gist options
  • Save spetroll/3a109b8838d65cc0e9e27cc3bf6c749f to your computer and use it in GitHub Desktop.
Save spetroll/3a109b8838d65cc0e9e27cc3bf6c749f to your computer and use it in GitHub Desktop.
useStateContext
export function createStateCtx<A>(
defaultValue: A
): [
() => {
state: A
update: Dispatch<SetStateAction<A>>
},
FunctionComponent<{}>
] {
type UpdateType = React.Dispatch<React.SetStateAction<typeof defaultValue>>
const defaultUpdate: UpdateType = () => defaultValue
const ctx = createContext({ state: defaultValue, update: defaultUpdate })
const Provider: FunctionComponent = props => {
const [state, update] = useState(defaultValue)
return <ctx.Provider value={{ state, update }} {...props} />
}
const useCtx = () => {
const c = useContext(ctx)
if (!c) {
throw new Error('useCtx must be inside a Provider with a value')
}
return c
}
return [useCtx, Provider] as [typeof useCtx, typeof Provider]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment