Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React context work without actual component

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

What am I not understanding or doing wrong?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading