Render Prop: Using Render Props with React.PureComponent
Using Render Props with React.PureComponent
//bad practice
class Mouse extends React.PureComponent {
// Same implementation as above...
}
class MouseTracker extends React.Component {
render() {
return (
<div>
<h1>Move the mouse around!</h1>
{/*
This is bad! The value of the `render` prop will
be different on each render.
*/}
<Mouse render={mouse => (
<Cat mouse={mouse} />
)}/>
</div>
);
}
}
//good practice
class MouseTracker extends React.Component {
// Defined as an instance method, `this.renderTheCat` always
// refers to *same* function when we use it in render
renderTheCat(mouse) {
return <Cat mouse={mouse} />;
}
render() {
return (
<div>
<h1>Move the mouse around!</h1>
<Mouse render={this.renderTheCat} />
</div>
);
}
} Using a render prop can negate the advantage that comes from using React.PureComponent if you create the function inside a render method because the shallow prop comparison will always return false for new props, and each render in this case will generate a new value for the render prop.
Semantic portal