If you don’t already know, the basic building blocks of React are known as components. They are chunks of code that can be reused and compiled to make user interfaces or UIs. React is a great language and React Native, a language used for mobile applications, is just as great. However, one complication that comes with any React application as how to pass data from one component to another. This is known as props in React, but what if the component kept getting larger? What if there are so many components that passing props through different components becomes a nightmare, and you the developer have to make sure that everything is perfect and one small props error as we go from component to component can break the whole thing???
Do I sound like I’m speaking from experience?
Thankfully, there is a way to better pass props directly from a specific component to another. In React this is called Context.
Let’s pretend we are looking at a tree of React components:
The initial component that renders is App.js and within that, we can dictate which components are rendered, and render other components inside of those components, etc. Now is we wanted to pass props through these components, we’d have to go through parent to children. Which can make things difficult. For example if the bottom-center component had props that we wanted to pass to the bottom-left component, we’d have to go back up the parent tree and back down to the proper child. This is known as prop drilling and well… it kinda sucks.
This is where Context comes into play. Passing props using Context looks a little bit like this:
While props passes information directly from parent to child, Context passes information from a parent directly to a nested component. That means that overall less code will have to be written. That being said, setting up Context can be a bit complicated, but it’s worth it.
I like to keep any Context in a separate folder where I can easily organize everything. Context is created like so:
import React from 'react';const myContext = React.createContext();export default myContext;
In the Context that we have created, we can then create all sorts of functions and export them to be imported by whatever components we want to have them. If you’re already React-savvy this may sound a lot like Redux and its use of dispatch and reducers!
We also need to set up a Provider, which helps to well …provide whichever Context we create.
On any component we want to use our Context on, we simply import it like we would any other component.
import myContext from './context/myContext;
Also I like to wrap my App.js component in the provider as well:
This may be an over simplification of Context and there is a lot more to talk about, but the over all statement is using Context works extremely well to provide information to nested components in a React application. It requires much less code and any programmer should have it in their tool belt.