Back to all notes
use() with Context : Conditional Context Reads in React 19
Read context with the new use() hook, even inside conditions and loops.
Introduction
The new use() hook in React 19 lets you read context directly from the context object, even inside conditions and loops. It’s a more flexible alternative to useContext.
Why this matters
useContext must be called unconditionally at the top level. In React 19, use() lets you read context more flexibly, including conditionally, which can simplify dynamic UI.
The problem
With useContext, you can’t read context inside conditions, and providers typically use .Provider syntax.
Inefficient approach
Top-level useContext and .Provider reduce flexibility:
import { createContext, useContext } from "react";
const ThemeContext = createContext(null);
function Button({ show, children }) {
const theme = useContext(ThemeContext); // must be top-level
if (!show) return null;
return <button className={"button-" + theme}>{children}</button>;
}
function App() {
return (
<div>
<h1>Use Hook with Context</h1>
<ThemeContext.Provider value="dark">
<Button show={true}>Sign up</Button>
<Button show={false}>Log in</Button>
</ThemeContext.Provider>
</div>
);
}
export default App;
The solution
Move the context read inside the conditional and use the context object directly.
import { createContext, use } from "react";
const ThemeContext = createContext(null);
function Button({ show, children }) {
if (show) {
const theme = use(ThemeContext);
const className = "button-" + theme;
return <button className={className}>{children}</button>;
}
return null;
}
function App() {
return (
<div>
<h1>Use Hook with Context</h1>
<ThemeContext.Provider value="dark">
<Button show={true}>Sign up</Button>
<Button show={false}>Log in</Button>
</ThemeContext.Provider>
</div>
);
}
export default App;
Step-by-step
- Define your context:
const ThemeContext = createContext(null). - Read it conditionally with
use(ThemeContext)inside the branch that renders. - Provide the value using the context object directly
<ThemeContext value="...">. - Keep reads close to where values are actually needed.
Tips
- Keep context values stable; avoid recreating objects every render.
- Prefer coarser context for theme/locale; finer context for dynamic data.
- Validate that your tooling and runtime support React 19
use().
Knowledge base
Problem snippet:
const theme = useContext(ThemeContext);
<ThemeContext.Provider value="dark">...</ThemeContext.Provider>
Solution snippet:
const theme = use(ThemeContext);
<ThemeContext value="dark">...</ThemeContext>