1import React from "react";
2import ReactDOM from "react-dom";
3
4// Create a Context
5const NumberContext = React.createContext();
6// It returns an object with 2 values:
7// { Provider, Consumer }
8
9function App() {
10 // Use the Provider to make a value available to all
11 // children and grandchildren
12 return (
13 <NumberContext.Provider value={42}>
14 <div>
15 <Display />
16 </div>
17 </NumberContext.Provider>
18 );
19}
20
21function Display() {
22 // Use the Consumer to grab the value from context
23 // Notice this component didn't get any props!
24 return (
25 <NumberContext.Consumer>
26 {value => <div>The answer is {value}.</div>}
27 </NumberContext.Consumer>
28 );
29}
30
31ReactDOM.render(<App />, document.querySelector("#root"));
32
33
34
35//now with useContext the same page look like this
36// import useContext (or we could write React.useContext)
37import React, { useContext } from 'react';
38
39// ...
40
41function Display() {
42 const value = useContext(NumberContext);
43 return <div>The answer is {value}.</div>;
44}
1const themes = {
2 light: {
3 foreground: "#000000",
4 background: "#eeeeee"
5 },
6 dark: {
7 foreground: "#ffffff",
8 background: "#222222"
9 }
10};
11
12const ThemeContext = React.createContext(themes.light);
13
14function App() {
15 return (
16 <ThemeContext.Provider value={themes.dark}>
17 <Toolbar />
18 </ThemeContext.Provider>
19 );
20}
21
22function Toolbar(props) {
23 return (
24 <div>
25 <ThemedButton />
26 </div>
27 );
28}
29
30function ThemedButton() {
31 const theme = useContext(ThemeContext);
32 return (
33 <button style={{ background: theme.background, color: theme.foreground }}>
34 I am styled by theme context!
35 </button>
36 );
37}