Introduction of Context API

Learn about the Context API in React and the application that we’ll be working on.

Introduction to TypeScript in React applications

Using TypeScript in any large React application provides a level of safety that’s worth the additional effort overusing JavaScript. TypeScript can comb through all of our components and confirm that we’re passing in all the props each component requires, and it makes sure they’re the types we assume they are and not something unwanted, like undefined. But there are some cases where even that trade-off is questioned—particularly when using the Context API. Let’s look at how to navigate some of the challenges of using createContext and useContext with TypeScript.

Overview of Context API

We assume you’re familiar with the Context API, but let’s do a quick summary anyway. The Context API in Reacthttps://react.dev/learn/passing-data-deeply-with-context is a built-in state management tool that allows easy data sharing throughout a component tree. It enables us to avoid prop drilling, the process of passing data from top to bottom through intermediate components.

With the Context API, we create a Context object with two properties: a Provider component—which wraps the part of our application’s component tree that needs access to our data—and a Consumer component for reading that data.

These days, we often don’t use the Consumer directly, instead using the useContext hook to access the context’s value, regardless of the level of each in the component hierarchy. The useContext hook is a much cleaner abstraction than trying to access the value from the Consumer in a render prop. This makes state and function sharing between components more convenient and efficient, especially in larger applications. In fact, the React documentationhttps://react.dev/reference/react/createContext#returns goes as far as to mention that the Consumer is “an alternative and rarely used way to read the context value.”

Get hands-on with 1400+ tech skills courses.