Mark As Completed Discussion

Context and useContext Hook

In React, the Context API is used for sharing data between components without passing props through every level.

The Context API comes with a hook called useContext that makes it easy to consume data from a context.

To create a context, you can use the createContext method from the React library:

JAVASCRIPT
1const MyContext = React.createContext();
2```+
3
4To provide a value to the context and make it available to child components, you can use the `Provider` component and pass the value as a prop:
5
6```javascript
7function App() {
8  const value = "Hello, World!";
9
10  return (
11    <MyContext.Provider value={value}>
12      {/* Child components here */}
13    </MyContext.Provider>
14  );
15}

To consume the context and access the value in a child component, you can use the useContext hook:

JAVASCRIPT
1function ChildComponent() {
2  const value = React.useContext(MyContext);
3
4  return (
5    <div>{value}</div>
6  );
7}

In the example provided, we create a context MyContext and provide a value of Hello, World! using the Provider component. Then, in the ChildComponent, we consume the context using the useContext hook and display the value.

Feel free to explore and experiment with the Context API and the useContext hook to efficiently manage global state and share data across multiple components.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment