-
Notifications
You must be signed in to change notification settings - Fork 49.9k
Description
Do you want to request a feature or report a bug? Feature request / question
According to React docs, there are 2 ways to avoid passing props through many levels:
- (New) context API
- Composition (Inversion of control)
When using the new context API, a consumer component must know, and explicitly import, a context.
This raises a quite big disadvantage comparing to the legacy context API:
Such component can't be reusable with different contexts (unless making a prop only version of this component, and wrapping it with another one that uses the context directly).
In fact, it means that a component can't be "contextual" and reusable (by different contexts) at the same time.
Using composition in many cases feels wrong for solving this, quoting the docs:
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.
Example of a component I struggle to understand why it should now import a context:
import * as React from "react"
import * as propsTypes from "prop-types"
export class Link extends React.PureComponent {
static contextTypes = {
navTo: propsTypes.any
}
handleClick = (e) => {
e.preventDefault()
const {path} = this.props
this.context.navTo(path)
}
render() {
const {path, ...props} = this.props
return <a href={path} onClick={this.handleClick} {...props} />
}
}If it was already discussed or answered, I apologize, couldn't find any related issues.