Skip to content

Instantly share code, notes, and snippets.

@nandorojo
Last active September 21, 2024 19:51
Show Gist options
  • Save nandorojo/22732522a160d4e7e91c7d853b4ba4f3 to your computer and use it in GitHub Desktop.
Save nandorojo/22732522a160d4e7e91c7d853b4ba4f3 to your computer and use it in GitHub Desktop.
A much better createContext, usable before React 19, with good TypeScript Types
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),
}
)
}
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