Created
May 19, 2019 13:26
-
-
Save spetroll/3a109b8838d65cc0e9e27cc3bf6c749f to your computer and use it in GitHub Desktop.
useStateContext
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
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