Say I have a parent component and one child component.
The props
has ten keys, but child needs only three.
What is the better way to pass props to child component?
class Parent extends Component {
render() {
{ /*pass all the ten keys into child*/ }
<Child {...this.props} />
}
}
or
class Parent extends Component {
render() {
{ /*pass only the needed keys into child*/ }
<Child key1={key1} key2={key2} key3={key3}/>
}
}
No, it's a bad idea usually. In general, it's better to just pass the component what it needs:
You can use lodash's
_.pick
function:<Child {...(_.pick(this.props, ['key1', 'key2', ...]))} />
Passing all the props generally isn't a good idea. More props means more things that will cause the child component to unnecessarily re-render. However, it can be convenient to use the spread operator on a subset of those props. For example, a parent component may receive a lot of props, but doesn't use most of them and instead hands all but one or two off to a child component. Consider this example using something like redux-form:
The outer form component only cares about the submit function. Other props indicating whether the form is dirty, valid, etc, would be used by the
<SaveButton />
to determine whether or not to disable the button.This is convenient because we avoid having to declare props for a component that doesn't use them. We just pass them through. But as stated previously, use this pattern with caution, making sure you're aware of which props you're actually handing down, because it could cause performance issues or even side effects.
In fact, I'd go so far as to say that if you find yourself passing props down through a hierarchy frequently, you probably have a design problem and should be leveraging your redux store more efficiently.