Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Using context and childContext in React

When working with React in a deeply nested hierarchy, often times you will find yourself in a situation where you need to pass down props from the parent as is to the children and the grandchildren. Although passing down properties is great, but writing code in such a manner encourages relying on memory to pass down the necessary props, and that’s not really a good use of your brain.Fortunately, React provides a way to make this task easier.

React has something called as Child contexts that allows a parent element to specify a context – aka a set of properties – which can be accessed from all of its children and grandchildren via the this.context object.

There are 2 aspects to how you would go about implementing this in your code.

  1. In the parent, the getChildContext method is used to return an object that is passed own as the child context. The prop types of all the keys in this object must also be defined in the childContextTypes property of the parent.
  2. Any child that needs to consume the properties passed down from its parents must whitelist the properties it wants to access via the `contextTypes’ property.

Here’s an example of how this works

One may argue that this makes the code a bit more verbose, because now you end up creating an additional key contextTypes on every child component. However, the reality is that you can specify the `contextTypes’ property on a mixin. That way you can avoid rewriting the whitelisting boilerplate code by simply using the mixin on all the child components that need to access those properties from its context.


Ryan Sukale

Ryan is just a regular guy next door trying to manage his life and finances.

You may also like...

  • Alex

    there a mistake at line 24? return { name: “I am the parent” }; instead of return { bar: “I am the parent” };

    • tutorialhorizon

      Updated! Thanks for letting me know.

  • Shaurya Arora

    Shouldn’t line 24 read: return { bar: “I am the parent” };

  • Andy Pai

    Awesome, thanks!