- I have two function component (component1) and it’s a main component and (component2) which i want to grap state data from it
import { useState, createContext, useContext } from "react";
import ReactDOM from "react-dom/client";
const TestContext = createContext();
function Component1() {
const test = useContext(TestContext);
return (
<h1>{`${test}`}</h1>
);
}
function Component2() {
const [test, setTest] = useState("From Component 3");
return (
<TestContext.Provider value={test}>
<Component1 />
</TestContext.Provider>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Component1 />);
In this question:
- I want to use only useContext Hook to bring state
- I want Component1 is the rendered component.
I try a lot but always the result is "undefined"
2
Answers
To ensure that
Component1
receives the context value fromComponent2
, we need to make sure thatComponent1
is rendered within theTestContext.Provider
provided byComponent2
.modified version:
Component1
is rendered within theTestContext.Provider
provided byComponent2
.Component2
provides the context value to its children, includingComponent1
.Component1
consumes the context value using theuseContext
hook.Now, when you render
Component2
,Component1
will receive the context value provided byComponent2
.Here it is why it says undefined.
<Component1/>
you have to render the<Component2/>
With this change,
Component2
will be the initially rendered component, and it will wrapComponent1
with theTestContext.Provider
, providing the state value.Component1
can then access the state value through theuseContext
hook.