React 04: Context API


Docs

lingo

  • "Components subscribing to state" ?


Context API

TLDR: app-wide states that you can inject anywhere


Context: How To

Contexts come with a .Provider component that can also take in a value to be made available to child components – without having to prop drill the value.

Child components, acting as Consumers, may subscribe to a Context’s value from their closest parent Provider with React’s useContext() hook.

Components subscribing to a Context will receive the value for the Provider closest to them in the application tree.

Providers may be given an object containing the React state and its corresponding state updater function. Subscribing child components may then use the state updater function to update the state for the Context.

Three parts:

  • Context providers

  • Context wrappers

  • useContext Hook


Context: Example 1: Without Context API


Context: Example 1: With Context API


Context: Example 1: With Context API + Wrapper


Context: Example 1: With Context API + Wrapper + 2 Buttons

ThemeContext.js

App.js

ContactItem.js


Context: Example 3

App.js

ThemeContext.js

ContactsSection.js

Last updated