add proxy example to context boilerplate

This commit is contained in:
Triston Armstrong 2024-09-04 07:34:18 -04:00
parent f0b085b8c7
commit fabd88c644

View File

@ -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()` 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")
}
}
)
)
```