DEV Community

Anders Hornor
Anders Hornor

Posted on

Context the super picker upper!

Coding with React can be a tedious typing exercise if a complex app has more than a few layers of components. To avoid unnecessary typing a newish addition to React the context API allows can help.

To explain a little more, Context allows one to pass information through deeply nested component trees without having to pass props through every level of the tree. By spending a small amount of extra time at the outset of a project one can avoid unnecessary clutter and typing in their project throughout. Context works similarly to props in that one defines variables in parent components that they want to have access to in its child components. with context though instead of having to identify which variables one wants to pass between parent and child components the variables are defined in the highest level component and can then be accessed throughout any children. There are a few ways to establish and access the context of a component tree but I am only going to cover one in this blog, the Component.contextType method of implementation.

Implementation

To showcase the power of the context API take imagine a deeply nested component tree like so.
An app that renders a top level component
App
A top level component that renders a component
HighestLevelCompenent
which renders another component
MiddleLevelCompenent
which renders another component
OtherMiddleLevelCompenent
which renders an input
Bottom

Implementation

Now with context you can define the context in the top level component by using react.createContext and avoid having to pass in props.

Context

All together looks like so:

HighestLevelCompenent with Context

then pass the context into the grandchild that you want to access the value of the context with a ExampleContext.Provider sandwich.

OtherMiddleLevelCompenent

When you render the bottom level component you now have access to the value of the context set in the top level component

Bottom

wham bam thank you mam!
Look at this web app! so simple!
Input

#Context

To clarify this is a reduced example that demonstrates a very basic implementation of the power of the react context API. There are other ways to implement this same functionality with context as well as other functionalities of context that can be implemented alongside this basic demonstration. I encourage you to look into the other capabilities of context in the react documentation as well. Thanks for reading :)

Top comments (0)