LoginSignup
0
0

More than 1 year has passed since last update.

React 描写(レンダー)の性能向上方法

Last updated at Posted at 2022-01-08

shouldComponentUpdate

仮に、コンポーネントが一千個あるいはそれ以上ある場合、レンダーの性能が低下になりがちで、

レンダーが必要ないコンポーネントを制御するためには、「shouldComponentUpdate」を使えば済ませます。

shouldComponentUpdate(nextProps,nextState)

 ・戻り値:boolean。True→Not Update, False→Update.

 ・トリガー:コンポーネントの更新時(forceUpdateを除く)

PureComponent

PureComponentの使い方はReact.Componentと似ています。React.Componentの場所をReact.PureComponentに書き換えるだけで良いです。

両者の違いは、PureComponentは「shouldComponentUpdate」を実装しています。更新前後のProps、Stateの値を自動的に比較してくれます。ただし、その比較は浅く比較(shallow compare)だけです。

どういうことと言うと、Value Typesの比較なら、それらの値を比較します。それに対して、Reference Typesの比較なら、参照先だけを比較します、属性は比較しません。

Value Types の比較

let wallet = 0
let newWallet = wallet
newWallet = 2
console.log(wallet === newWallet) //false

Reference Typesの比較

const obj = { wallet: 0 }
const newObj = obj
newObj.wallet = 2
console.log(newObj === obj)  //true

//同じ参照先のため、新しいオブジェクトの属性をどう変えても、戻り値はTRUEになります。

Reference Typesの属性を比較させる方法

属性をそのまま修正するではなく、新しい属性を追加する。

const newObj = { ...state.obj, wallet: 2 }  //ES6のスプレッド構文
setState({ obj: newObj })

//配列の場合
//push,unshiftを使うではなく、concat,sliceなどで新配列を返す

this.setState({
    obj: [...this.state.obj, { newObj }]
})
0
0
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
0
0