useContext
useContext is a Hook that reads a value shared through context. Context is a way to share a value with many components at once.
Making context
The starting value is Guest.
const UserContext = createContext('Guest');Giving a value
The Provider gives Ada to the components below it.
<UserContext.Provider value="Ada">
<Greeting />
</UserContext.Provider>Reading the value
The Greeting reads the shared value.
const user = useContext(UserContext);
return <p>Hello, {user}!</p>;Example
import { createContext, useContext } from 'react';
const UserContext = createContext('Guest');
function Greeting() {
const user = useContext(UserContext);
return <p>Hello, {user}!</p>;
}
export default function App() {
return (
<UserContext.Provider value="Ada">
<Greeting />
</UserContext.Provider>
);
}
Key points
- Context shares a value with many components at once.
- A Provider is the component that gives the value.
- Components below the Provider can read the value.
- useContext reads the nearest value above the component.
In this example, the file makes a UserContext with Guest as its starting value. The Greeting reads the shared value with useContext. The App wraps the Greeting in a Provider with the value Ada. The page shows the greeting with Ada in it.
Note
A component with no Provider above it reads the starting value.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What value does the Greeting show in the example?