Context Home
Understanding This Work
All files in the /pages
directory need to be ReactNodes. The context pages all live under /pages/context
but can import files, components, and context from /components/context
. Next steps for this page are to create working examples of each of the levels articulated in the context section.
Links
Quick Discussion
If you look at the file for Basic Context you can see that there are some red squigglies - TypeScript doesn't like it. The reason is that my context could be null
. In level 2, we fix that.
The file for Guarded Context looks quite similar to the first one (because TypeScript won't build the app if it's wrong) but it has a guard. This is a safe context usage.
The Split Context is a good pattern. I've combined Levels 3 & 4 because Level 4 is just Level 3 with safe reference to the context.
The Context Factory context is interesting. I like that it allows me to pretty quickly create a brand new context. Once you finish the factory, here is how I quickly spun up a new counter context:
import { createSafeContext } from "./context-factory"
type CounterState = {
count: number;
}
export const [FactoryCounterProvider, useCounter] = createSafeContext<CounterState>('Counter')
And then to use it, it's just like a custom context. I wrap my target component in the provider and then use my custom hook in the component that needs it.