I'm working on some project where I need to add react child components dynamically. While this task may seem to be easy to complete, I'm concerned about the efficiency of my approach. I surfed the internet and found several solutions that have the same design pattern as mine. Still, I'm doubting myself of efficiency.
Below is my example:
class Container extends Component{
constructor(props){
super(props)
this.setState = {
children = []
}
this.addChild = this.addChild.bind(this)
}
addChild(){
this.setState({
children: [...this.state.children,
<div>
<h1> My number is this.state.children.length} </h1>
</div>
}
render() {
return
<div>
<button onClick={this.addChild}> Add child </button>
{this.state.children.map( child => child)}
</div>
}
}
This example is quite simple. But when you have a complex structure, where components have other components that change state, have events listeners and deep structure, Component's state value will contain a huge amount of code and this component will re-render everything on each addition. On 100th addition, it will make 99 unnecessary re-renders.
Of course, I can use Vanilla JS or JQuery to append new components, but I do not find it to be smart decision. I'd like to keep consistency and solve the problem with React tools.
What are your thoughts? What patterns would you suggest?
Aucun commentaire:
Enregistrer un commentaire