add proxy example to context boilerplate
This commit is contained in:
parent
f0b085b8c7
commit
fabd88c644
@ -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")
|
||||
}
|
||||
}
|
||||
)
|
||||
)
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user