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
Welcome to FullStack Labs. We use cookies to enable better features on our website. Cookies help us tailor content to your interests and locations and provide many other benefits of the site. For more information, please see our Cookies Policy and Privacy Policy.

Make useContext Data More Discoverable with Typescript

Written by 
,
Make useContext Data More Discoverable with Typescript
blog post background
Recent Posts
Integrating GitHub Actions and Docker for a Java Project
Businesses Must Seize the AI Wave (Or Cease to Exist)
Code, Deploy, Succeed: Next.js, Firebase, and Tailwind CSS Unleashed

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.

Table of contents

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}"></companycontext.provider>
<usercontext.provider value="{props.user}"></usercontext.provider>
<myapplication></myapplication>


);
}

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></react.fragment>
<title titletext="{company.name}/"></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.

-- 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>>({});   </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.

-- CODE language-jsx keep-markup --
type AppProps = {  
company: Company;  
user: User;
}

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


);
};

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.

Written by
People having a meeting on a glass room.
Join Our Team
We are looking for developers committed to writing the best code and deploying flawless apps in a small team setting.
view careers
Desktop screens shown as slices from a top angle.
Case Studies
It's not only about results, it's also about how we helped our clients get there and achieve their goals.
view case studies
Phone with an app screen on it.
Our Playbook
Our step-by-step process for designing, developing, and maintaining exceptional custom software solutions.
VIEW OUR playbook
FullStack Labs Icon

Let's Talk!

We’d love to learn more about your project.
Engagements start at $75,000.

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