3

This is my first time using usecontext,and i got stuck with this problem,where the usecontext returns the initial value and not the passed value.

This is my App.js

import { useContext } from 'react';
import {userprop} from './Context'

function App() {

  const value = useContext(userprop)
  console.log(value)
  return (
    <div >
      
      
    </div>
  );
}

export default App;

This is my Context.js

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

export const userprop  =createContext(0)

function Context(){
    const [a,seta] = useState(2)
    return(
        <userprop.Provider value={3}>
            <App/>
        </userprop.Provider>
    )
}
export default Context;

Iam getting the output as 0 and not 2 !! How can i solve it?

1 Answers1

1

You are approaching it the wrong way. The Context Provider should wrap everything that wants to consume the context.

Making minimal changes to your code :

import { useContext } from "react";
import { userprop } from "./Context";

function App() {
  const value = useContext(userprop);
  console.log(value);
  return <div></div>;
}

export default App;

Also, you are not passing the state value into the context, but instead a hard coded number 3. So that needs change too:

import React, { useState, createContext } from "react";
import App from "./App";

export const userprop = createContext(0);

function Context() {
  const [a, seta] = useState(2);
  return (
    <userprop.Provider value={a}>
      <App />
    </userprop.Provider>
  );
}
export default Context;

Now, you have to mount Context as your main component into the div instead of App though.

Link

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39