Make useContext Data More Discoverable with Typescript

Written by Brian Smith

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';

export const UserContext = React.createContext({});
export const CompanyContext = React.createContext({});

// ...

import { UserContext, CompanyContext } from './appContexts';
 
const App = (props) => {
 return (
   <CompanyContext.Provider value={props.company}>
     <UserContext.Provider value={props.user}>
       <MyApplication />
     </UserContext.Provider>
   </CompanyContext.Provider>
 );
}
    

Now assume a component like TitleConent makes use of user and company to display the company.name 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 (
    <React.Fragment>
      <Title titleText={company.name}/>
      <UserMenu name={user.fullName} onLogout={user.logout} />
    </React.Fragment>
  );
};
  

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;
  // etc...
  };
  
export type Company = {
  name: string;
  location: {
    street: string;
    city: string;
    state: string;
  };
  // etc...
};
  

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.



    export const UserContext = React.createContext<Partial<User>>({});
    export const CompanyContext = React.createContext<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 => {
  return (
    <CompanyContext.Provider value={props.company}>
      <UserContext.Provider value={props.user}>
        <MyApplication />
      </UserContext.Provider>
    </CompanyContext.Provider>
  );
};     
  

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



Conclusion


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.

Let’s Talk!

We’d love to learn more about your project. Contact us below for a free consultation with our CEO.
Projects start at $25,000.

FullStack Labs
This field is required
This field is required
Type of project
Reason for contact:
How did you hear about us? This field is required