LoginSignup
0
0

childrenで受け取ったコンポーネントの再レンダリング

Posted at

はじめに

備忘録です。

勘違いしやすい再レンダリングの違い

ケース1はParentが再レンダリングされると、ChildComponentも再レンダリングされる
ケース2はParentが再レンダリングされてもChildComponentは再レンダリングされない

ケース2の時ChildComponentはHomeと親子関係を持っている、Homeが再レンダリングされればChildComponentも再レンダリングされる

ケース1 Parentに直接記述する
ParentとChildComponentは親子関係

export const Parent = () => {
  return <ChildComponent />
}

ケース2: propsのchildrenとしてChildComponentを渡す
ParentとChildComponentは非親子関係

export default function Home() {
  // childrenによる受け渡しなので、ParentとChildComponentに親子関係はない
  // ChildComponentはHomeと親子関係
  return (
    <Parent>
      <ChildComponent />
    </Parent>
  )
}

どこで使われているか

特に意識していなくてもuseContext使用時のProviderでこの仕組みを使用したことがある方が多いのではないでしょうか?
この時の<App /><TestProvider>を定義しているコンポーネントと親子関係であり、<TestProvider>と<App />に親子関係はありません。
私はこの挙動についての理解が足りず、TestProviderで定義されたstateを更新したら全てのComponentが再レンダリングされてしまうではないか!!と誤解し、調べるにあたりました。
他の箇所で再レンダリングの最適化も行うことができるので、覚えておくとどこかで使えるかもしれないですね。

<TestProvider>
  <App />
</TestProvider>
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