The way I actually use works well but my props keep growing and I wondering if I can group them into one single state and pass it to the child, this is my code:
<Panel
uniqueIDs={uniqueIDs}
userID={userID}
loading={loading}
premium={premium}
percent={percent}
total={total}
until={until}
user={user}
done={done}
/>
After the render I define those variable like so :
let { loading, empty, total, uniqueIDs, slice, percent, until, ok, user, premium, data, keys, done, userID } = this.state;
Can i just send this.state
variable? I made a little bit of research I didn't find any solution to my issue, I know I can use third-party libraries to manage state but I am trying to keep it simple.
The way I actually use works well but my props keep growing and I wondering if I can group them into one single state and pass it to the child, this is my code:
<Panel
uniqueIDs={uniqueIDs}
userID={userID}
loading={loading}
premium={premium}
percent={percent}
total={total}
until={until}
user={user}
done={done}
/>
After the render I define those variable like so :
let { loading, empty, total, uniqueIDs, slice, percent, until, ok, user, premium, data, keys, done, userID } = this.state;
Can i just send this.state
variable? I made a little bit of research I didn't find any solution to my issue, I know I can use third-party libraries to manage state but I am trying to keep it simple.
- stackoverflow./questions/31452684/… – channasmcs Commented May 16, 2019 at 5:59
- Possible duplicate of How to pass function groups as props in React? – channasmcs Commented May 16, 2019 at 5:59
- Put props into an object and pass the object as a prop to ponent – mstfyldz Commented May 16, 2019 at 6:02
2 Answers
Reset to default 5you can make an object for the props you are sending and can use spread operator
let props = {
uniqueIDs : uniqueIDs,
userID:userID,
loading:loading,
premium:premium
}
<Panel {...props} />
In panel ponent you can use this.props.uniqueIDs ans so on.
Yes, you definitely could just pass your entire state-variable into your child-ponent as multiple properties
<Child {...this.state}/>
This would be perfectly acceptable.
If your state is {id: 1, name: 2}
You would still be able to access the props in your child-ponent as
props.id or this.props.id
props.name or this.props.name
As a note you should be cognizant of ponent re-rendering. If you make many updates to the state in your parent-ponent this will also cause your Child ponent to re-render a lot as well, which could have performance issues.
To workaround this, make sure to employ methods like ponentDidUpdate()
for class-ponents and react-hooks
for functional ponents. These can help control the flow of re-rendering.