Reputation: 43
Which is better in passing props?
title="sample" description="sample desc"
I know its situational. but which do you prefer in terms of dynamic, backend ready(API integration), and performance? sorry if I describe it badly but I believe you get my point.
All your advice is welcome and correct. Thanks!!
Edit: Also what are the cons and pros
Upvotes: 2
Views: 1345
Reputation: 26
I guess it depends on what you need in your React component. I generally prefer to keep my components as clean (pure) as possible and only pass whatever is needed as props.
I suggest reading the how to guide on thinking in react and react components/props on the reacts.org website. Keeping in mind that in JS atomic values (strings, numbers, booleans, etc.) are passed by value and objects (arrays are objects too) are passed by reference (see here and here), passing an object means that you always run the risk of mutating the object in the child component, which directly contradicts the following strict rule: "All React components must act like pure functions with respect to their props.".
EDIT: That said, it still depends on your requirements. If you adhere to not mutating the passed object, it should be fine.
This should give you a fairly good guideline on how to design your components.
Upvotes: 1
Reputation: 53874
Let's see pros/cons for each option, given the component User
:
const User = ({name,lastName}) => <>...</>
const props = {
name: 'Jhon',
lastName: 'Cena'
};
<User {...props}/>
const props = {
name: 'Jhon',
lastName: 'Cena',
id: 325013213
};
// User component might be updated in future releases and might use id unexpectedly.
<User {...props}/>
const props = {
user: 'Jhon',
lastName: 'Cena'
};
<User name={user} lastName={lastName}/>
name={user}
)className={className}
)const props = {
name: 'Jhon',
lastName: 'Cena'
};
<User {...{ name,lastName }}/>
On my codebase, I'm trying to combine:
const props = {
className: 'user',
user: 'Jhon',
lastName: 'Cena'
};
<User {...{className,lastName} name={user}/>
// Although you totally can write like this,
// I find it confusing
<User {...{className, name:user,lastName}/>
Upvotes: 1
Reputation: 350
I would say as objects would be better. As I would be sort of package thing that u can easily transform to json if u need to send over an API. Passing in an object also set it to a standard naming convention. When passing as separate props u have the flexibility to rename them but it might cause human error. If u are passing it as an object, u are defining the naming from the start and u will not change it. So when referencing to the object in multiple components u don't have to refer what did u define it when u are passing it in ur props
Upvotes: 1
Reputation: 11
In my opinion, I prefer passing the whole object as props. Because it's easy to use and transform whatever you want.
Upvotes: 1