traintocode

Context API

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.

Exercise
Add a second property "age" into the context as a number, then display it in the <UserProfile> component in place of xxx.
    You cannot do the coding exercises on this device, visit this page on a larger screen.
    context.tsx
    Loading...
    UserProfile.tsx
    Loading...