Can you pass state through multiple levels of the component tree?

Question

In the context of this exercise, can you pass state through multiple levels of the component tree?

Answer

Yes, you can pass state through any number of component levels. To do this, you can simply continue to pass it down as props through each level.

// In the topmost level, we pass the value to the first child
return (
  <Child propName={this.state.someValue} />
)

// In the Child component, we pass this prop to the GrandChild
return (
  <GrandChild propName={this.props.propName} />
)

// This repeats down each component level
return (
  <GreatGrandChild propName={this.props.propName} />
)
10 Likes

You can also pass it through multiple levels without passing it down through each level on the way by using React Context.

6 Likes

PSA, context should be used sparingly because it makes component reuse more difficult. Context is primarily used when some data needs to be accessible by many components at different nesting levels.

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

5 Likes