React.js pure render performance anti-pattern

Pure render?

Why?

The anti-pattern

class Table extends PureComponent {
render() {
return (
<div>
{this.props.items.map(i =>
<Cell data={i} options={this.props.options || []} />
)}
</div>
);
}
}
this.props.options || []
const default = [];
class Table extends PureComponent {
render() {
return (
<div>
{this.props.items.map(i =>
<Cell data={i} options={this.props.options || default} />
)}
</div>
);
}
}

Functions create identities too

class App extends PureComponent {
render() {
return <MyInput
onChange={e => this.props.update(e.target.value)} />;
}
}
class App extends PureComponent {
update(e) {
this.props.update(e.target.value);
}
render() {
return <MyInput onChange={this.update.bind(this)} />;
}
}
class App extends PureComponent {
constructor(props) {
super(props);
this.update = this.update.bind(this);
}
update(e) {
this.props.update(e.target.value);
}
render() {
return <MyInput onChange={this.update} />;
}
}

Use Reselect in Redux connect(mapState)

let App = ({otherData, resolution}) => (
<div>
<DataContainer data={otherData} />
<ResolutionContainer resolution={resolution} />
</div>
);
const doubleRes = (size) => ({
width: size.width*2,
height: size.height*2
});
App = connect(state => {
return {
otherData: state.otherData,
resolution: doubleRes(state.resolution)
}
})(App);
import {createSelector} from “reselect”;const doubleRes = createSelector(
r => r.width,
r => r.height,
(width, height) => ({
width: width*2,
height: heiht*2
})
);

Conclusion

--

--

--

I write code and jump from airplanes

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Esa-Matti Suuronen

Esa-Matti Suuronen

I write code and jump from airplanes

More from Medium

How to build a Circle Progress from scratch with React

Part 1: how to build your own JS framework

Using the State Hook in React: useState() Hook

Building React Custom Hooks