LoginSignup
0
0

More than 3 years have passed since last update.

[React] <Component {...props} /> なpropsの渡し方

Posted at

tl;dr

タイトルのようなpropsの渡し方でも無駄に再レンダリングが起きることはない、ということの確認の記事。

code

スプレッド演算子でオブジェクトを展開すると「新しいオブジェクト」が生成される。なので、レンダリング最適化の観点で、無駄に再レンダリングが起きそうにも見える。

だが、実際は「新しいオブジェクト」が生成されるだけで、要素については新しい値なわけではない。

const func = () => console.log('hello world')
const props = { func }
const newProps = { ...props }
props.func === newProps.func // => true

なので、レンダリング最適化されていれば、この渡し方でも無駄にレンダリングが起きることはない

// count が増加してもChildが再レンダリングされることはない
const App = () => {
  const [count, increment] = React.useReducer(prev => ++prev, 0)
  const func = React.useCallback(() => console.log('hello world'), [])
  const props = { func }
  return(
    <div>
      <button onClick={increment}>increment({count})</button>
      <Child {...props} />
    </div>
  )
}

const Child = React.memo(({func}) => <button onClick={func}>CLICK_ME</button>)

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