Skip to content

Instantly share code, notes, and snippets.

@yuripramos
Created December 21, 2021 18:57
Show Gist options
  • Save yuripramos/a5ef8982e2ffaf43ab38d464a5608590 to your computer and use it in GitHub Desktop.
Save yuripramos/a5ef8982e2ffaf43ab38d464a5608590 to your computer and use it in GitHub Desktop.
createCtx typescript
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