Make useContext Data More Discoverable with Typescript

Written by

React’s useContext hook allows developers to manage global application state without the need for a full state-management system, although many such libraries now use useContext under the hood. Data used in deeply-nested components that does not share the same parent component is a great use case for useContext. Storing this data with useContext saves developers from prop-drilling, an anti-pattern that passes large amounts of data down from parent components to deeply-nested components, and all the components in between.

A downside of this pattern is that the type and shape of the data being passed via context is not entirely clear. For example, suppose we have the following contexts: user and company defined at the app root. The location of the company and user data is not relevant. Let’s assume they have been initialized and passed in from a useEffect call.

import React, { useContext } from 'react';
‍exportconst UserContext = React.createContext({});
‍exportconst CompanyContext = React.createContext({});
import { UserContext, CompanyContext } from './appContexts'; 

const App = (props) => {
 return (   
 <companycontext.provider value="{}"></companycontext.provider>
 <usercontext.provider value="{props.user}"></usercontext.provider>

Now assume a component like TitleContent makes use of user and company to display the and user.fullName. At this point, a developer new to the project would not know what other properties exist on the user or company objects, because nothing in the code conveys this within the file. The names and types of properties available on each object are not available.

import React, { useContext } from 'react';
import { UserContext, CompanyContext } from './appContexts';

const TitleContent = () => {
 const user = useContext(UserContext);  
 const company = useContext(CompanyContext);    

 return (    
 <title titletext="{}/"></title>
 <usermenu name="{user.fullName}" onlogout="{user.logout}"></usermenu>

In a standard prop-drilling scenario, prop-types could be used to convey the shape and type of the data. However, we are using context in this example, so we are unable to convey this information through the code.

Enter Typescript

Typescript is a strongly typed superset of Javascript that will allow us to convey the types and shapes of useContext data. Check out the Typescript docs to learn more. We can leverage Typescript’s Type Aliases to define the properties available on the user and company object. We will define the types here so they can be imported and shared across the application.

export type User = {  
 id: number;  
 fullName: string;  
 firstName: string;  
 lastName: string;  
 isAdmin: boolean;  
 logout: () =>void;  
export type Company = {  
 name: string;  
 location: {    
 street: string;
 city: string;    
 state: string;  };  

The Typescript Partial allows the context to initialize with an empty object. The data will later initialize fully through the context Provider.

Use the following syntax to add the above Type Aliases to the createContext calls.

exportconst UserContext = React.createContext<partial<user>>({});   </partial<user>exportconst CompanyContext = React.createContext<partial<company>>({});</partial<company>

Next, define the App component in Typescript and give it the appropriate types. Note the introduction of React.FC and AppProps, which expect Company and User types. The types defined above for the Company and User objects are reused and ultimately passed into the provider’s value prop to set the context’s values.

type AppProps = {  
 company: Company;  
 user: User;}

const App: React.FC<appprops> = (props): JSX.Element => {  </appprops>
 return (    
 <companycontext.provider value="{}"></companycontext.provider>
 <usercontext.provider value="{props.user}"></usercontext.provider>

Now when we leverage user or company in another component, our IDE (Visual Studio Code shown) will show auto-completion properties automatically.


By leveraging Typescript we can make data stored with the useContext hook to make the available properties more discoverable. The value of adding types with Typescript is not restricted to the useContext hook. useReducer, useState and other hooks, components and functions can also take advantage of strong typing.

At FullStack Labs, we pride ourselves on our ability to push the capabilities of cutting-edge frameworks like React. Interested in learning more about speeding up development time on your next project? contact us.

Frequently Asked Questions