triston-notes/Cards/dev/Create Context Boilerplate.md

98 lines
2.8 KiB
Markdown
Raw Normal View History

2023-10-21 23:52:54 +00:00
up:: [[TypeScript]]
X:: [[JavaScript]]
tags:: #boilerplate
2023-10-21 23:52:54 +00:00
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:
```tsx
import React, { createContext, useContext } from 'react';
interface MyContextType {
// type your context values here
}
const MyContext = createContext<MyContextType>({} as MyContextType);
export const useMyContext = () => useContext(MyContext)
export function MyContextProvider(props: React.PropsWithChildren) {
const value = {
// Add your context values here
};
return (
<MyContext.Provider value={value}>
{props.children}
</MyContext.Provider>
);
}
```
To use this context provider, you can wrap your root component with the **`MyContextProvider`** component:
```tsx
import MyContextProvider from './MyContextProvider';
function App() {
return (
<MyContextProvider>
<div>
{/* Add your components here */}
</div>
</MyContextProvider>
);
}
```
This will make the **`MyContext`** object available to all components within the **`App`** component. To consume the context in a child component, you can use the **`useContext`** hook from the React API:
```tsx
import React, { useContext } from 'react';
import MyContext from './MyContext';
function MyChildComponent() {
const context = useContext(MyContext);
// Use the context values here
}
```
Keep in mind that the **`createContext`** method takes an optional default value as its first argument. This default value will be used if a **`Provider`** is not present for the context, so it's a good idea to specify a default value that makes sense for your context.
This usually looks like:
```tsx
const MyContext = createContext({}); // notice the empty object
```
You can even take it a step further and instead of using `const context = useContext()` inside your component, you can create a simple hook in your context file itself like so:
```tsx
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")
}
}
)
)
```