Answer
First you create the context using createContext, then you wrap the part of your app that needs access with a Provider component and give it a value, and finally any component inside that Provider can read the value using the useContext hook.
const UserContext = React.createContext(null);
function App() {
const [user, setUser] = useState({ name: 'Alice' });
return (
<UserContext.Provider value={user}>
<Profile />
</UserContext.Provider>
);
}
function Profile() {
const user = useContext(UserContext);
return <p>Hello, {user.name}</p>;
}Real-world example A shopping app creates a UserContext once, wraps its entire app in a Provider holding the logged in customer's details, and lets any component, like the header or the checkout page, read that same data easily.