Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useContext doesn't work when in same file

So not sure if this is exactly the problem, but wondering why this is happening when using contexts in the same file vs different files.

So here is the constant:

StartupContext.js

import React from "react";

export const StartupContext = React.createContext()

export const StartupProvider = ({ something, children }) => {
    return (
        <StartupContext.Provider value={{ something }}>
            {children}
        </StartupContext.Provider>
    )
}

No problems there. But when I run this:

App.js

function Root() {
  const { something } = useContext(StartupContext);

  return (
    <Text>Root {something}</Text>
  )
}

export default function App() {
  const [something, setSomething] = useState("ayyyy")

  return (
    <StartupProvider something={something}>
      <Root />
    </StartupProvider>
  );
}

I'll get this error:

TypeError: undefined is not an object (evaluating 'Context._context')

BUT

If I split into two files

App.js

import { Root } from "./Root";

export default function App() {
  const [something, setSomething] = useState("ayyyy")

  return (
    <StartupProvider something={something}>
      <Root />
    </StartupProvider>
  );
}

Root.js

export default function Root() {
  const { something } = useContext(StartupContext);

  return (
    <Text>Root {something}</Text>
  )
}

It will work just fine. Why is this happening?

like image 734
thestephenstanton Avatar asked Mar 20 '26 15:03

thestephenstanton


1 Answers

Oh man. It was something totally different.

I was importing on the single file:

import StartupContext from "./app/contexts/startupContext";

which was wrong, what I should have had was this:

import { StartupContext } from "./app/contexts/startupContext";
like image 51
thestephenstanton Avatar answered Mar 23 '26 08:03

thestephenstanton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!