Context (React)

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.

Problem

Using context, we can avoid passing props through intermediate elements:

Solution

What is children prop?

Children is a prop this.prop.children that allow you to pass components as data to other components, just like any other prop you use. Component tree put between component’s opening and closing tag will be passed to that component as children prop.

There are a number of methods available in the React API to work with this prop. These include React.Children.map, React.Children.forEach, React.Children.count, React.Children.only, React.Children.toArray.

A simple usage of children prop looks like this:

If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context

Component composition

Components use the special children prop to pass children elements directly into their output:

This lets other components pass arbitrary children to them by nesting the JSX:

You can also specify where you want children props to go. In our case, we can position prop children to be placed in certain areas.

We can even specialize it:

Inversion of Control

It might feel redundant to pass down the user and avatarSize props through many levels if in the end only the Avatar component really needs it. It’s also annoying that whenever the Avatar component needs more props from the top, you have to add them at all the intermediate levels too.

One way to solve this issue without context is to pass down the Avatar component itself so that the intermediate components don’t need to know about the user or avatarSize props:

This inversion of control can make your code cleaner in many cases by reducing the amount of props you need to pass through your application and giving more control to the root components. However, this isn’t the right choice in every case: moving more complexity higher in the tree makes those higher-level components more complicated and forces the lower-level components to be more flexible than you may want.

You’re not limited to a single child for a component. You may pass multiple children, or even have multiple separate “slots” for children, as documented here: