Member-only story

Practical Usage of React’s Context API

Ben Grunfeld
3 min readJun 1, 2020
React Context API

The Context API in React allows you to pass props to descendant components that aren’t direct children. If the prop updates, the components that uses it re-renders.

Previously, if you had the following components structure: Parent -> Child -> Grandchild, you would have to pass props from Parent to Child, and then from Child to Grandchild for them to be available in the Grandchild.

The Context API allows you to skip this intermediate step (threading props through each level of components) and make the props directly accessible to the Grandchild, or even Great Grandchild.

This should only be used for global settings like theme, language, user info, etc. Regular prop hierarchies should still be used in most cases.

Usage

I’m only going to focus on using Functional Components, because I do not like working with Javascript classes.

There are two main ways to use Context — with a Context.Consumer and with the useContext hook.

Personally, I prefer to use the useContext hook instead of Context.Consumer, because I feel it’s bulky and clunky, and in general makes the code a little less readable.

Here’s a full working example:

Using the Consumer

--

--

Ben Grunfeld
Ben Grunfeld

Written by Ben Grunfeld

I’m a Front End Engineer who loves React, NextJS, and GraphQL. Looking for a developer in #Israel? Contact me at: https://www.linkedin.com/in/bengrunfeld/

Responses (1)