useContext Hook
What are useContext Hooks in React?
In React, the `useContext` hook is part of the Hooks API and is used for consuming a React context. Context provides a way to pass data through the component tree without having to pass props down manually at every level.
Create Context
You need to create a context using `React.createContext`. This returns an object with two components: `Provider` and `Consumer`.
app/page.tsx
1import { createContext } from "react";
2
3const StateContext = createContext()
Provide Context
Use the `Provider` component to wrap the part of your component tree where you want to make the context available.
app/page.tsx
1// Example providing the context
2<MyContext.Provider value={/* some value */}>
3 {/* Your component tree */}
4</MyContext.Provider>
Consume Context
Now, you can use the `useContext` hook to access the value provided by the context within your functional component.
app/page.tsx
1// Example consuming the context
2import React, { useContext } from 'react';
3
4function MyComponent() {
5 const contextValue = useContext(MyContext);
6
7 // Use contextValue in your component
8}
9
Here's an example when all tied together:
app/page.tsx
1// Example usage of context and useContext
2
3// Step 1: Create a context
4const MyContext = React.createContext();
5
6// Step 2: Provide the context
7function App() {
8 return (
9 <MyContext.Provider value={'Hello from Context!'}>
10 <MyComponent />
11 </MyContext.Provider>
12 );
13}
14
15// Step 3: Consume the context
16function MyComponent() {
17 const contextValue = useContext(MyContext);
18
19 return <div>{contextValue}</div>;
20}