Last active
September 21, 2024 19:51
-
-
Save nandorojo/22732522a160d4e7e91c7d853b4ba4f3 to your computer and use it in GitHub Desktop.
A much better createContext, usable before React 19, with good TypeScript Types
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 as create, useContext } from 'react' | |
export function createContext<T>(initial?: T) { | |
const ctx = create<T>(initial ?? (null as any)) | |
return Object.assign( | |
function Provider(props: React.ComponentProps<typeof ctx.Provider>) { | |
return <ctx.Provider {...props} /> | |
}, | |
ctx, | |
{ | |
use: () => useContext(ctx), | |
} | |
) | |
} |
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 } from 'react' | |
// no need to pass a default value if you want invalid consumers to crash anyway, which is usually desired | |
const Context = createContext<{ color: string }>() | |
export function Page() { | |
return ( | |
// no need to do .Provider | |
<Context> | |
<Child /> | |
</Context> | |
) | |
} | |
function Child() { | |
// no need to import useContext separately | |
const { color } = Context.use() | |
return null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment