P E N C I L
Login
How to handle React context in a reliable way 

Source: https://medium.com/react-ecosystem/how-to-handle-react-context-a7592dfdcbc

Context — no pun intended —

One-way data flow is one of the most compelling traits of React. It makes your app easier to reason about. You can figure out exactly what props are being passed just by looking at your component. You can even get more out of it adopting the container vs presentational component pattern.

But, if you’ve used React for a while, chances are that you’ve found a situation where you want to pass data through the component tree without having to pass the props down at every level.

React has a feature to solve this problem: context.

Probably you’re getting profit of it even without realize it. Due to some of the most used libraries in the React ecosystem take advantage of it: React-Router, React-Redux, and many more.

But, it comes with a price and you have to be careful. React’s documentation warn us about it:

https://facebook.github.io/react/docs/context.html

This post is intended to show you how to use React context reliably. Outlining the most common pitfalls and how to avoid them.

How does React context work?

First you need a context provider component. Which is no more than a normal component that requires childContextTypes and getChildContext:

childContextTypes: static property that allows you to declare the structure of the context object being passed to your component’s descendants. Similar fashion to propTypes but not optional.

getChildContext: prototype method that returns the context object to pass down the component’s hierarchy. Every time the state changes or the component receives new props this method will be called.