Jon Rumsey

An online markdown blog and knowledge repository.


Project maintained by nojronatron Hosted on GitHub Pages — Theme by mattgraham

React UseContext

Overview

Props:

Context:

Context API

When passing props to deeply nested components, props can become more difficult to manage, passing props through many children to the place the data needs to go in the hierarchy.

Context API allows specifying pieces of data available to all components without having to pass data through each component.

React.createContext:

In React Class Components, Context components must wrap the child components and the function variable must be passed-in (and out) of the Context Provider and Consumer, respectively.

In React Function Components, useContext hook allows bypassing the Component wrapping, which simplifies code.

UseContext Hook

Pass your custom Context to 'useContext' hook:

This bypasses having to wrap Components in Consumer and Provider elements.

Notes

Reference

Examples were borrowed from videos and the WDS Blog.

WebDev Simplified - useContext in 13 Minutes.