From fabd88c644a7b239e365e191297ed2e98eef8ca2 Mon Sep 17 00:00:00 2001 From: Triston Armstrong Date: Wed, 4 Sep 2024 07:34:18 -0400 Subject: [PATCH] add proxy example to context boilerplate --- Cards/dev/Create Context Boilerplate.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/Cards/dev/Create Context Boilerplate.md b/Cards/dev/Create Context Boilerplate.md index 2a33d43..95ba4d7 100644 --- a/Cards/dev/Create Context Boilerplate.md +++ b/Cards/dev/Create Context Boilerplate.md @@ -1,6 +1,6 @@ up:: [[TypeScript]] X:: [[JavaScript]] -tags:: #boilerplate +tags:: #boilerplate To create a boilerplate context provider in React 18, you can use the **`createContext`** method from the React API and then use the **`Provider`** component to provide the context to its children. Here's an example: @@ -72,3 +72,26 @@ const useMyContext = () => useContext(MyContext) ``` Which will allow you to **[destructure](https://www.geeksforgeeks.org/destructuring-of-props-in-reactjs/#:~:text=What%20is%20Destructuring%3F,variables%20created%20by%20the%20developer.)** your values: `const {someValue} = useMyContext()` + +--- + +### Bonus +If you try to use the `useContext` hook outside of the context provider, React will just be like: "eh.. lgtm!" + +You probably dont want that. A cool thing you can do is add a `Proxy` object as an argument to your `createContext` call +instead of an empty object. + +Here's an example: + +```tsx +const MyContext = createContext( + new Proxy( + {}, + { + get(){ + throw new Error("useMyContext must be used from inside Provider") + } + } + ) +) +```