Introduction

Let's have a look at how to effectively produce global variables that can be passed around the application with ease.

We'll cover the following

What is a Context API?

The React Context API has been treated as somewhat of an afterthought for a long time. It was first implemented as a prototype and treated experimentally, but later added to React in version 16.3.

The Context API has been designed to distribute data from a component to data consumers without explicitly passing props through the whole component tree. This is immensely useful for language settings as well as a global styling schema (Theme).

The Context API consists of two main actors:

  1. Context Provider
  2. Context Consumer

The Provider acts as a central instance for the corresponding data structure, whereas the Consumer can consume this data at any point in the app. It forms a sort of “semi-global” data instance that is only valid in certain parts of the component hierarchy.

This does not mean that the data structure cannot be complex. It is not limited to strings or arrays but can consist of complex data. An application can have an unlimited amount of Contexts (for example, one for the user-chosen language, one for the styling schema, etc.), and Providers can be reused with different values. But let’s take it one step at a time.

Get hands-on with 1200+ tech skills courses.