Menu

react-context-typesafe: missing context providers as lint errors instead of runtime crashes

#reactjs#redditreactjs#children#context#user
Reading 0:00
15s threshold

You know the pattern: createContext<User | null>(null) , then a useAuth() hook that throws "useAuth must be used within AuthProvider", and every consumer either trusts that or null-checks. A missing provider is a runtime error you find when that screen renders, or when a test does.

I wanted it to be a lint error instead, so I built an oxlint plugin that checks it across the whole program:

``` const AuthContext = createContext<User | null>(null);

function Children() { const user = use(AuthContext); return <p>{user?.name}</p>; }

root.render( <AuthContext value={user}> <Children /> {/* ok */} </AuthContext>, );

root.render(<Children />); // ^ react-context(require-provider): <Children> needs AuthContext // (use(AuthContext) at Children.tsx:4), but no <AuthContext> provider is above it. ```

Children needs no annotations. Requirements are inferred from use , useContext , <Ctx.Consumer> and static contextType .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.