FullStack Labs

Please Upgrade Your Browser.

Unfortunately, Internet Explorer is an outdated browser and we do not currently support it. To have the best browsing experience, please upgrade to Microsoft Edge, Google Chrome or Safari.
Upgrade

Make useContext Data More Discoverable with Typescript

Written by 
Brian Smith
,
Senior Software Engineer
Make useContext Data More Discoverable with Typescript
blog post background
React Developer Salaries
Comparing Hourly Rates Between Software Consultancies
React Native App Of The Week: Speedy Cash
Building REST-based React Native Offline Apps
Speed, Quality, Price: Choose Two When Building Custom Software
Remote Usability Testing

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.

-- CODE language-jsx keep-markup --
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={props.company}>
<UserContext.Provider value={props.user}>
<MyApplication />
</UserContext.Provider>
</CompanyContext.Provider>
);
}

Now assume a component like TitleContent 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.

-- CODE language-jsx keep-markup --
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.

-- CODE language-jsx keep-markup --
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.

-- CODE language-jsx keep-markup --
exportconst UserContext = React.createContext<Partial<User>>({});  
exportconst 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.

-- CODE language-jsx keep-markup --
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.

Brian Smith
Written by
Brian Smith
Brian Smith

As a Senior Software Engineer, I have a passion for great software and user interfaces. I take pride in writing code that is well-documented and designed. I have over 10 years of experience, most recently focusing on designing and implementing full-stack applications using node.js, React.js, Mongo, and Elasticsearch. Prior to FullStack, I worked as a software engineer in various roles at UC Davis, UC Berkeley, and MIT. I graduated Summa Cum Laude with a BS in computer science from California State University of Sacramento.

FullStack Labs Icon

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 $50,000.

company name
name
email
phone
Type of project
Reason for contact
How did you hear about us?
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.