Reputation: 57
I am working on a React app, and I need to modify the parent's state from a child component. Of course, I could simply write a function in the parent, and pass it as a prop to the child (like everyone else seems to be doing). However, I tried instead to pass the entire parent as a prop to the child, so that the child can freely modify the parent's state.
This is how my parent looks with its children:
{this.state.entries.map(entry => (
<UserEntry
...
mainThis={this}
/>
))}
Notice how I pass the entire parent into the child as a prop with a this
. From my child code, I can then modify the parent's state with a simple this.props.mainThis.setState()
.
Of course, this worked, and I am really pleased with myself. However, I am wondering why people are not doing this. Would it affect performance in the long run, or something?
Upvotes: 2
Views: 82
Reputation: 6221
I am wondering why people are not doing this. Would it affect performance in the long run, or something?
It will make your code hard to debug, understand and test because of tight coupling between parent and child. This is also against encapsulation principles because a child component shouldn't know anything about state and internal implementation of parent component and vise-versa. Components should be loosely coupled.
This has nothing to do with code performance but it will surely affect performance of you team in the long run.
Bonus Read: 7 architectural attributes of a reliable react component
Upvotes: 0
Reputation: 3704
As your codebase grows bigger and more complex, you will find yourself trying to find a way to manage the complexity. It is important for reducing bugs and adding new features. Doing this opens up a can of worms.
Heres an example. You do this in one parent to child. The child also has a list of elements that it passes the this
reference to. Finding out which child element is updating the state that causes a bug from data becomes a chore. You won't have a good place to drop a debug point to see values, and the job will be harder
A big advantage of React is the idea of a component. React makes the component re-usable and self contained. If you start passing the this
reference, your parent component becomes tightly coupled to the child component. It becomes harder to tease apart the functions of each component.
Feel free to experiment with this pattern. When the codebase reaches the tipping point, you will feel the pain of this design choice very quickly.
Upvotes: 2