React Pattern: Extract Child Components to Avoid Binding
Cory House
1.6K35

Hi Cory.

Dima Kishmareishvili has mentioned the closure method which I prefer to use as well.

But still I can’t follow the point. You say that your method lets avoid rendering of children if state of parent changes in irrelevant (for its children) way. But as far as I know React reconciliation process starts from bottom, so children will be rerendered anyway (if no render control methods used)?

I’ve add setInterval function which changes the state of parent so it cause children rerendering in any case.

Please explain in details your point. And what you think about ‘closure’ method in snippet?

Thanks for your articles and courses!

import React from 'react';
import { render } from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [{ id: 1, name: 'Cory' }, { id: 2, name: 'Meg' }],
ext: 1
};
this.interval = setInterval(() => {
this.setState(prevState => {
return { ext: prevState.ext + 1 }
})
}, 2000);
}
deleteUser = id => () => {
this.setState(prevState => {
return { users: prevState.users.filter( user => user.id !== id)}
})
}
clearInterval = () => {
clearInterval(this.interval);
}
render() {
return (
<div>
<h1>Users</h1>
<h3>{this.state.ext}</h3>
<ul>
{
this.state.users.map( user => {
return (
<li key={user.id}>
<input type="button" value="Delete" onClick={this.deleteUser(user.id)} />
{user.name}
</li>
)
})
}
</ul>
<div>
<button onClick={this.clearInterval} >
Clear inteval
</button>
</div>
      </div>
);
}
}
export default App;
render(<App />, document.getElementById('root'));
Like what you read? Give Victor Storozhenko a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.