Sub topic 2
Where You Can Call `use`
Assume you know function components, props, promises, useContext, and the basic purpose of Suspense. React’s use API has different calling rules from ordinary Hooks such as useState and useContext.
Conditions, loops, and early returns
You can call use inside a condition, loop, or after an early return. React still requires the call to happen while a component or custom Hook is rendering. Do not call it inside an event handler, nested callback, or try/catch block.
import { use } from 'react';
function RecipeList({ recipePromises }) {
if (recipePromises.length === 0) {
return <p>No recipes found.</p>;
}
const recipes = [];
for (const recipePromise of recipePromises) {
recipes.push(use(recipePromise));
}
return (
<ul>
{recipes.map((recipe) => (
<li key={recipe.id}>{recipe.name}</li>
))}
</ul>
);
}The early return is valid. The loop is also valid because use is designed to support these cases. The promises should still have stable identities across renders. Creating new promises during every render can cause repeated suspension or fetching.
Reading context with `use`
Pass a context object to use to read its nearest provider value. This is similar to useContext, but use can be called after a condition.
import { createContext, use } from 'react';
const ThemeContext = createContext({ color: 'navy' });
function Heading({ children }) {
if (children == null) {
return null;
}
const theme = use(ThemeContext);
return <h1 style={{ color: theme.color }}>{children}</h1>;
}
export function App() {
return (
<ThemeContext.Provider value={{ color: 'darkgreen' }}>
<Heading>Account</Heading>
</ThemeContext.Provider>
);
}Here, Heading avoids reading the context when it has no content. With useContext, placing the context read after that conditional return would violate the usual Hook rules. With use, it is allowed.
use(ThemeContext) reads the closest provider above Heading. If no provider exists, React uses the default value passed to createContext.
Exercise
Why is use(ThemeContext) valid after an early return, while the same placement with useContext(ThemeContext) is invalid?
Show answer
The use API supports calls in conditions and after early returns. useContext follows the ordinary Hook rule that calls must remain unconditional and in the same order on every render.