triston-notes/Cards/dev/Create Context Boilerplate.md
2024-09-04 07:34:18 -04:00

2.8 KiB

up:: TypeScript X:: JavaScript 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:

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:

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:

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:

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:

const useMyContext = () => useContext(MyContext)

Which will allow you to destructure 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:

const MyContext = createContext(
  new Proxy(
    {},
    {
      get(){
        throw new Error("useMyContext must be used from inside Provider")
      }
    }
  )
)