LoginSignup
21
10

More than 5 years have passed since last update.

React.memoでrecomposeのpureが要らなくなった話

Posted at

先日React v16.6.0がリリースされました。
https://reactjs.org/blog/2018/10/23/react-v-16-6.html

リリースされた機能の中にReact.memoというものがあるのですがこれでrecomposeのpureが要らなくなりそうだという話です。

recompose.pureとは

Reactでは再レンダリングを繰り返すとパフォーマンスが落ちるわけですが、多くの場合はshouldComponentUpdateを実装して、propsが同じ場合は再レンダリングをしないよといった具合でパフォーマンスの向上をはかります。
React v15.3からトップレベルAPIでPureComponentというものが追加されました。これはshouldComponentUpdateをデフォルト実装したComponentで、propsをshallow equalしてパフォーマンス向上の実装を楽にしてくれます。

import React, { PureComponent } from 'react'

class Pure extends PureComponent {
  render() {
    return (
      <p>pure component</p>
    )
  }
}

これをHOCで実装できるようにしたのが、HOCによってライフサイクルメソッドを追加できるようにするライブラリのrecomposeです。これのpureメソッドを利用することでSFCなどでも楽に実装することができます。
https://github.com/acdlite/recompose

import React from 'react'
import { pure } from 'recompose'

const Pure = pure(() => (
  <p>pure component</p>
))

React.memoとは

ここで出てくるのが、v16.6で追加されたReact.memoです。これはPureComponentshouldComponentUpdateの実装を関数コンポーネントでもラップするだけで出来るようにしたものです。
propsが変わった場合のみ再レンダリングされます。

import React from 'react'

const Pure = React.memo(() => (
  <p>pure component</p>
))

Reactは今後どんどんSFCになっていきますね。

21
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
10