Read: Class 33 - 401-advanced-javascript-dania/amman-javascript-401d1 GitHub Wiki

Context API

In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

When to Use Context Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.

  • Context Context provides a means of passing state down the component tree through a Provider/Consumer relationship.

At as high a level as makes sense, a “provider” can make it’s state available, along with means of altering it (methods).

  • In a class style component, you can attach to context in 2 ways: Wrap your component with, and use a function to “get” the context object itself, which is this.state from the provider component.

Statically declare a connection to the context provider and then use this.context to connect to state from the context provider In a functional component, you can use the useContext() hook to tap right in.

Returns and provides access to whatever your context provider exports

In this example, our context provider gives us a title property and a changeTitleTo() method that we can call. This is much easier than referencing the context variable inline as you normally would.

Note – the context API is still critically important even with this hook available. Not every React shop is using hooks, so know both ways.