React Context Using TypeScript

suhas murthy
Level Up Coding
Published in
3 min readApr 25, 2020

--

ReactJS is simple and it efficiently updates and renders just the right components when your data changes. React uses a component-based approach which manages its own state.

Typically in the React app, data is passed top-down (parent to child) via props. But this can complicate things. Imagine we have 10 components and the user has updated his preferred language. Now we need to pass this information to all 10 components which are complicated and time-consuming.

To overcome this problem statement we use Context. React documentation says Context provides a way to pass data through the component tree without having to pass props down manually at every level.

The most important question is when to use context?

Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.

But using context makes reusability of component difficult. So during the design stage, we need to be extra careful and make sure the reusability of the component is not disturbed.

Demo Project

Demo project which allows Dark mode and gives information about your favorite IPL team 😀

As I am writing this article during the lockdown and missing cricket 😒 I have built a simple App on IPL which gives you basic information about your favorite team and allows you to change the theme as well.

Note: I have not explained about state, props, and UI used in this application as they are very basic and has no complications

The code can be downloaded here

Context can be divided into three parts

  1. Creating a context
  2. Providing the created context (To the components)
  3. Consuming the context (In any of the child components)

1.Creating a context

We can create a context using the createContext API. Keep in mind that the component that subscribes to the context will read the current context value from the closest provider. We can import it from react:

import React, {createContext} from "react";

In our example, we require two contexts — one is to handle theme and another is to update the team across the application.

TeamContext.tsx 
export const TeamContext = createContext<{team:string,changeTeam:any}>({team:"rcb",changeTeam:null})
ThemeContext.tsx
export const ThemeContext = createContext<themeState>({ isDarkMode: false, toggleTheme: null,});

2. Providing the context

Every context comes with a Provider component. This allows the consuming components to subscribe to the context changes.

After including Context provider to our context our code will look like this

Note: These two files have methods to update the theme and team details as well

3. Consuming the Context

Getting value from context is pretty straight forward in the class based component. Below is the sample code to get the context in the class based component. I will get to the functional component later.

const {isDarkMode} = this.context

But the challenging part is when we want to consume two contexts in one component. In our example, Navbar needs both the context as we are changing color as well as updating the team logo. According to documentation, we need to consume by subscribing

<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>

To handle this I have included higher order component in TeamContext.tsx

The above steps increase the code as well as complicates the implementation. So the best way to handle this is by using a functional based component. This avoids higher-order component and we can simply consume any number of context in our component by using useContext hook:

const {isDarkMode, toggleTheme} = useContext(ThemeContext);    
const {team} = useContext(TeamContext);

You can find the entire solution in Github

For class-based components refer here. The functional-based components example can be found here.

This is my first article so if you have any feedback please let me know in the comment section. Hope this article gave you some basic understanding on React Context

--

--