-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReactContext.js
More file actions
38 lines (33 loc) · 1.08 KB
/
ReactContext.js
File metadata and controls
38 lines (33 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*The Context API in React provides a way to share values like themes, user authentication status,
or other global states between components without explicitly passing them through props at every level of the component tree.
It consists of two main parts: the Context object and the Provider component.*/
import React, { useState } from "react";
import MyContext from "./Components/MyContext";
import ChildComponent from "./Components/Consumer";
function App() {
const [value, setValue] = useState("Default Value");
return (
<MyContext.Provider value={value}>
<div>
<h1>App Component</h1>
<ChildComponent />
</div>
</MyContext.Provider>
);
}
export default App;
import React from "react";
const MyContext=React.createContext();
export default MyContext;
import React, { useContext } from "react";
import MyContext from "./MyContext";
function ChildComponent() {
const contextValue = useContext(MyContext);
return (
<div>
<h2>Child Component</h2>
<p>Context Value: {contextValue}</p>
</div>
);
}
export default ChildComponent;