Skip to content

Commit e09ff1c

Browse files
authored
Better use(Context) example in 19 blog (#6789)
1 parent 8cbed3e commit e09ff1c

File tree

1 file changed

+14
-14
lines changed

1 file changed

+14
-14
lines changed

src/content/blog/2024/04/25/react-19.md

+14-14
Original file line numberDiff line numberDiff line change
@@ -274,24 +274,24 @@ To fix, you need to pass a promise from a suspense powered library or framework
274274

275275
</Note>
276276

277-
You can also read context with `use`, allowing you to read Context conditionally:
277+
You can also read context with `use`, allowing you to read Context conditionally such as after early returns:
278278

279-
```js {1,8,10}
279+
```js {1,11}
280280
import {use} from 'react';
281-
import LightThemeContext from './LightThemeContext'
282-
import DarkThemeContext from './ThemeContext'
283-
284-
function ThemedPage({theme, children}) {
285-
let currentTheme;
286-
if (theme === 'dark') {
287-
currentTheme = use(DarkThemeContext);
288-
} else {
289-
currentTheme = use(LightThemeContext);
290-
}
281+
import ThemeContext from './ThemeContext'
282+
283+
function Heading({children}) {
284+
if (children == null) {
285+
return null;
286+
}
287+
288+
// This would not work with useContext
289+
// because of the early return.
290+
const theme = use(ThemeContext);
291291
return (
292-
<Page theme={currentTheme}>
292+
<h1 style={{color: theme.color}}>
293293
{children}
294-
</Page>
294+
</h1>
295295
);
296296
}
297297
```

0 commit comments

Comments
 (0)