Reputation: 492
In React, normally, we pass props to child component by following way:
const Parent = ({ foo, bar, baz, myFoo, myBar, myBaz }) => <Child foo={foo} bar={bar} baz={baz} /> (1)
Currently I figured out an alternative way to do this:
const Parent = ({ foo, bar, baz, myFoo, myBar, myBaz }) => <Child {...{ foo, bar, baz }} /> (2)
IMO, (2) saves a lot of time and typing effort. However:
Update 1: I have added myFoo, myBar, myBaz
in Parent's props. Please note that I do not want to spread all props to Child component, because it's considered as bad practice that results in unnecessary props in Child component.
Upvotes: 3
Views: 1843
Reputation: 7062
You could rewrite your code to:
const Parent = (props) => <Child {...props} />
and that's actually very common to do in react.
If you need foo
, bar
or baz
somewhere else you could write it like this:
const Parent = (props) => {
const { foo, bar, baz } = props;
// do something with foo, bar or baz
return <Child {...props} />;
}
To come back to your questions:
1) No, that's not an anti pattern, but you should use approaches above instead (I never saw code similar to your example in any project so far). A disadvantage could be that you don't really now any more what you pass down to the Child
and that you might pass down more than you need. E.g. props
of Parent
could have an additional field like faz
and you would just pass it to the Child
and it would never use it.
2) I can't think about any meaningful performance issue here. In my projects I use this approach very often and I never noticed any performance problems.
Upvotes: 2
Reputation: 559
Why would it be consider anti-pattern ? After all this is where spread operator is useful, right ?
You should not care about performance. This will be transpiled to plain old javascript anyway(through babel or something similar). This is just syntactic sugar.
Upvotes: 0
Reputation: 3515
The only drawback about it is that sometimes is hard to understand, by using approach one, you're making the code more readable and explicit. Of course if you have some sort of documentation for the components, like storybook or something that will help the other devs to understand the props that the component needs, it does not matter to use the second approach (prop spreading), but to make things readable you should stick with the first one (declaring each prop one by one).
Check this eslint-react-plugin rule https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-props-no-spreading.md it summarizes why is better to use the first approach.
Upvotes: 1