The Context API in React allows passing data through the component tree without having to pass props down manually at every level. In TypeScript you can easily type the context values.
The context provider on the right defines a context value type of UserContextType
, it is used to create a context like this:
const UserContext = React.createContext<UserContextType | undefined>(undefined);
Notice the use of undefined to initialize the context. This is a TypeScript-friendly way to assert that the context value will always be provided by a provider component.
This pattern ensures that your context values are strongly typed, and any misuse or errors in accessing the context's values or functions will be caught at compile time.
"age"
into the context as a number, then display it in the <UserProfile>
component in place of xxx.