Home > Software engineering >  React context work without actual component
React context work without actual component

Time:08-02

Just when I thought I understood contexts, I don't again. I created a database context, mostly for no reason since it's a global that can be just used as a var, but I digress. I wanted to be React-y. Anyway the component looks like this

import { createContext, useContext } from "react";
import { Database } from "../lib/database/Database";

const db = new Database();

export interface DatabaseContextValues {
  db: Database;
}

export const DatabaseContext = createContext<DatabaseContextValues>({
  db,
});

export const DatabaseContextProvider: React.FC = (props) => {
  return (
    <DatabaseContext.Provider value={{ db }}>
      {props.children}
    </DatabaseContext.Provider>
  );
};

export const useDatabaseContext = () => useContext(DatabaseContext);

And on a random component I used it like this

export const MyThing = () => {
   const { db } = useDatabaseContext();
}

And it worked. And I thought great. And then some time later, I realized I never even created the component itself, eg in my App

const App = () => {
  return (
    <SafeAreaProvider>
      // woops, forgot provider, but doesn't matter
      <MyThing/>
    </SafeAreaProvider> 
  )
}

What am I not understanding or doing wrong?

CodePudding user response:

The provider role is to centralize and dispatch the context values for all children components. If you don't wrap child components in the provider, they will access to a new, 'unshared' context.

  • Related