Created
December 21, 2021 18:57
-
-
Save yuripramos/a5ef8982e2ffaf43ab38d464a5608590 to your computer and use it in GitHub Desktop.
createCtx typescript
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 * as React from "react"; | |
/** | |
* A helper to create a Context and Provider with no upfront default value, and | |
* without having to check for undefined all the time. | |
*/ | |
function createCtx<A extends {} | null>() { | |
const ctx = React.createContext<A | undefined>(undefined); | |
function useCtx() { | |
const c = React.useContext(ctx); | |
if (c === undefined) throw new Error("useCtx must be inside a Provider with a value"); | |
return c; | |
} | |
return [useCtx, ctx.Provider] as const; // 'as const' makes TypeScript infer a tuple | |
} | |
// Usage: | |
// We still have to specify a type, but no default! | |
export const [useCurrentUserName, CurrentUserProvider] = createCtx<string>(); | |
function EnthusasticGreeting() { | |
const currentUser = useCurrentUserName(); | |
return <div>HELLO {currentUser.toUpperCase()}!</div>; | |
} | |
function App() { | |
return <CurrentUserProvider value="Shawn"> | |
<EnthusasticGreeting /> | |
</CurrentUserProvider>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment