Reactでベンチマークテストするならreact-addons-perf

React でパフォーマンスが気になった時にレンダリングの時間をどうやって計測するんだろうと思ったら、公式にあった。

react-addons-perf というツールで計測できる。

以下、簡単なサンプルコード。

import React, { Component } from 'react'
import Perf from 'react-addons-perf'
import _ from 'lodash'

const randomStr = () => Math.random().toString(36).slice(-8)
const createListItem = () => ({
  text: randomStr()
})
const createList = (length) => new Array(length).fill(0).map(() => createListItem())

class ListItem extends Component {
  render () {
    let { text } = this.props.item
    return (
      <div>{ text }</div>
    )
  }

  // shouldComponentUpdate (nexProps) {
  //   return !_.isEqual(this.props.item, nexProps.item)
  // }
}

class App extends Component {
  constructor () {
    super()
    this.state = {
      list: createList(1000)
    }
  }

  render () {
    let { list } = this.state
    return (
      <div className='App'>
        <button onClick={this.start.bind(this)}>START</button>
        <div>
          {
            list.map(
              (item, i) => <ListItem key={i} item={item} />
            )
          }
        </div>
      </div>
    )
  }

  componentDidUpdate () {
    Perf.stop()
    Perf.printInclusive()
  }

  start () {
    Perf.start()
    let nextList = _.clone(this.state.list)
    nextList[0] = { text: 'aaaaaa' }
    this.setState({ list: nextList })
  }
}

export default App

ListItem コンポーネントに shouldComponentUpdate を定義するかどうがでレンダリングの時間が変わるかどうかを確かめた。1000個のアイテムがあって、その中の一つを更新するのにかかった時間。

shouldComponentUpdate をコメントアウトした状態

f:id:fuji_haruka:20170623220114p:plain

shouldComponentUpdate を入れた状態

f:id:fuji_haruka:20170623220119p:plain

けっこう変わる。renderが呼ばれた回数がわかる。親切だ。基本的に shouldComponentUpdate を定義するか PureComponent を使った方がいい。というか、使わない理由がない。