Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React, getting undefined as result while using useContext

I'm trying to get state and setState from the Store file but I get undefined. What's happening, and how do fix it?

import React, {createContext, useState} from 'react'
import Header from './Header'

export const Data = createContext()


function Store() {
  const [state, setState] = useState(false)
  const  value = {state, setState}

  return (
    <Data.Provider value={value}>
      <Header/>
    </Data.Provider>
  )
}

export default Store
import React, { useContext} from "react";
import { Data } from "./Store";

function Header() {
  const Store = useContext(Data)
  
  console.log(Store) // I get undefined

  return (
    <div>
    </div>
  );
}

export default Header;
like image 672
Noureddine Bachikh Avatar asked Jun 04 '26 07:06

Noureddine Bachikh


1 Answers

You are creating Store, but never calling it, that's the problem. Wrap App component inside Store and it would work. Working example of your link here.

index.js:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import Store from "./store";
import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <Store>
      <App />
    </Store>
  </StrictMode>
);

like image 139
yousoumar Avatar answered Jun 05 '26 21:06

yousoumar



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!