Skip to content

Commit abb61ac

Browse files
Add custom hook for context to avoid assertions
1 parent ac4ca4e commit abb61ac

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

README.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1486,11 +1486,19 @@ export const App = () => (
14861486
<AppCtx.Provider value={sampleAppContext}>...</AppCtx.Provider>
14871487
);
14881488

1489+
const useAppContext = () => {
1490+
const appContext = useContext(AppCtx);
1491+
if (!appContext) {
1492+
throw new Error("useApp must be used within <AppCtx.Provider>.");
1493+
}
1494+
return appContext;
1495+
};
1496+
14891497
// Consume in your app
14901498
import { useContext } from "react";
14911499

14921500
export const PostInfo = () => {
1493-
const appContext = useContext(AppCtx);
1501+
const appContext = useAppContext();
14941502
return (
14951503
<div>
14961504
Name: {appContext.name}, Author: {appContext.author}, Url:{" "}

docs/basic/getting-started/context.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,19 @@ export const App = () => (
2828
<AppCtx.Provider value={sampleAppContext}>...</AppCtx.Provider>
2929
);
3030

31+
const useAppContext = () => {
32+
const appContext = useContext(AppCtx);
33+
if (!appContext) {
34+
throw new Error("useApp must be used within <AppCtx.Provider>.");
35+
}
36+
return appContext;
37+
};
38+
3139
// Consume in your app
3240
import { useContext } from "react";
3341

3442
export const PostInfo = () => {
35-
const appContext = useContext(AppCtx);
43+
const appContext = useAppContext();
3644
return (
3745
<div>
3846
Name: {appContext.name}, Author: {appContext.author}, Url:{" "}

0 commit comments

Comments
 (0)