Use of Context API vs CloneElement for passing down props for direct descendent
Asked Answered
O

2

7

So, I have two components, one is always going to be a direct descendant of another. I want to pass props from parent component to the child. There could be more than one child components. There're two ways to achieve it.

React.Children.map(children, (child) =>
  React.cloneElement(child, { someProp: 'value' })
)

or using the Context API

<Context.Provider value={{ someProp: 'value' }}>
  {this.props.children}
</Context.Provider>

Both will result in the same DOM structure, however, Context API is slightly more code and will result in more React Components.

So which one is more performance oriented and recommended. I couldn't find any discussion related to this comparison, thus asking here.

Overhear answered 28/9, 2018 at 9:52 Comment(0)
A
1

The use of context API seems to be overkill for passing data to direct descendant.

If a child is aware that data will be passed from a parent (this is presumed by the use of <Context.Consumer>), it could use render prop pattern directly, e.g:

<Parent>{passedProps => <Child {...passedProps}/>}</Parent>

and

{children({ someProp: 'value' })};
Acacia answered 28/9, 2018 at 10:8 Comment(6)
How about multiple children? Does using Context API still overkill for more than one child?Overhear
It's no different. You could make parent support multiple render props (children can be a function or an array of functions), or even better, fit the children into single render prop, <Parent>{passedProps => <><Child {...passedProps}/><Child {...passedProps}/></>}</Parent>Acacia
This answer does not address the scenario proposedUdelle
@Udelle How so? This is exactly what the post shows, "So, I have two components, one is always going to be a direct descendant of another. I want to pass props from parent component to the child". If you have a similar case that differs in some way so it cannot be solved this way, consider asking a new question.Acacia
The question is about how to "inject" props into children, so you can use the components normally, nesting them. Your solution just makes the parent component use the child component everytime which is a completely different APIUdelle
@Udelle The question is about how to do this with 2 specific components, not just random components. In case your case differs, a solution may be different and will likely be more like the code in the OP.Acacia
M
0

The new Context API is really interesting and help us deal with prop-drilling and make the use of render props pattern more clear, but it comes with some “performance problems” due the unnecessary re-rendering. In fact, it isn’t a problem because the API comes with a way to work with this unnecessary re-rendering. see link if this helps and optimizing-performance-in-context api

Microsecond answered 28/9, 2018 at 10:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.