Skip to content

Commit 73b3d95

Browse files
Add custom hook for context to avoid assertions
1 parent 61f5609 commit 73b3d95

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
@@ -1529,11 +1529,19 @@ export const App = () => (
15291529
<AppCtx.Provider value={sampleAppContext}>...</AppCtx.Provider>
15301530
);
15311531

1532+
const useAppContext = () => {
1533+
const appContext = useContext(AppCtx);
1534+
if (!appContext) {
1535+
throw new Error("useApp must be used within <AppCtx.Provider>.");
1536+
}
1537+
return appContext;
1538+
};
1539+
15321540
// Consume in your app
15331541
import { useContext } from "react";
15341542

15351543
export const PostInfo = () => {
1536-
const appContext = useContext(AppCtx);
1544+
const appContext = useAppContext();
15371545
return (
15381546
<div>
15391547
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)