A context object identifies a shared value and connects its provider configuration with components that consume that value. It avoids passing state through intermediate components that do not use it, making it useful when many components across an application need rarely changing information such as the current user, theme, or language. section 8.0 section 8.3
Use a context object through a provider-and-consumer flow:
- Create and export the object with createContext, optionally supplying a default value. section 8.1.4 section 8.2.4
- Wrap the component subtree that needs the value with Context.Provider and pass the shared value through its value prop. section 8.1.4 section 8.3
- Read the value with useContext(Context); consumers re-render when that context value changes. section 8.1.4 section 8.2
- Split unrelated values into multiple contexts when consumers should update independently, and use custom providers to centralize shared-state management. section 8.2.3 section 8.3
Sharing the current user
Create UserContext with createContext(), provide the current user near the application root with <UserContext.Provider value={user}>, and read it inside BookingDetails with const user = useContext(UserContext). The component can then compare booking.bookerId with user.id and show an edit button only for the current user's booking. section 8.1.4
Listing 8.3 Creating and exporting a context object for our user value
import {createContext} from "react";
const UserContext = createContext();
export default UserContext;
Shows the minimal createContext import, object creation, and export pattern. section 8.1.4


