Member-only story
Practical Usage of React’s 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: