はじめに
この記事はReactの再レンダリングされる基本的な条件について簡単にまとめたものです.
再レンダリングされる条件
- stateの更新
- 親コンポーネントの再レンダリング
- contextの変化
stateの更新
stateが更新されるとコンポーネントが再レンダリングされます.
例:以下のコードでは,ボタンをクリックすることでcountが更新されることで,Counter
が再レンダリングされます.
const Counter = () => {
console.log("Counterが再レンダリングされました");
// `count` を管理する state
const [count, setCount] = useState(0);
return (
<div>
<h2>カウント: {count}</h2>
<button onClick={() => setCount(count + 1)}>増やす</button>
</div>
);
};
親コンポーネントの再レンダリング
親コンポーネントが再レンダリングされると子コンポーネントも再レンダリングされます.
例:以下のコードでは,ボタンクリックでcountが更新されることでParent
が再レンダリングされます.それにより,Child
も再レンダリングされます.
const Child = () => {
console.log("Childが再レンダリングされました");
return <div>子コンポーネント</div>;
};
const Parent = () => {
console.log("Parentが再レンダリングされました");
const [count, setCount] = useState(0);
return (
<div>
<h2>カウント: {count}</h2>
<button onClick={() => setCount(count + 1)}>増やす</button>
<Child />
</div>
);
};
よくある勘違い
子コンポーネントが再レンダリング条件として,propsが更新されること
と耳にしますが,これは.親コンポーネントが再レンダリングされているからです.
const Child = ({value}) => {
console.log("Childが再レンダリングされました");
return <div>子コンポーネント</div>;
};
const Parent = () => {
console.log("Parentが再レンダリングされました");
const [count, setCount] = useState(0);
const [value, setValue] = useState(0);
return (
<div>
<h2>カウント: {count}</h2>
<button onClick={() => setCount(count + 1)}>増やす</button>
<Child value={value} /> // propsが更新されるかどうかは関係なく再レンダリング
</div>
);
};
contextの変化
Context.Providerのvalueが変化すると,Providerのコンポーネントが再レンダリングされます.
// `Context` の作成
const CountContext = createContext(null);
// `Child1` で `count` を更新する
const Child1 = () => {
console.log("Child1が再レンダリングされました");
const { setCount } = useContext(CountContext);
return (
<div>
<h2>Child1</h2>
<button onClick={() => setCount((prev) => prev + 1)}>カウントを増やす</button>
</div>
);
};
// `Child2` も `count` を参照する
const Child2 = () => {
console.log("Child2が再レンダリングされました");
const { count } = useContext(CountContext);
return (
<div>
<h2>Child2</h2>
<p>カウント: {count}</p>
</div>
);
};
// `Parent` で `Context` を管理
const Parent = () => {
console.log("Parentが再レンダリングされました");
const [count, setCount] = useState(0);
return (
<CountContext.Provider value={{ count, setCount }}>
<h1>Parent</h1>
<Child1 />
<Child2 />
</CountContext.Provider>
);
};