React에서의 리렌더링과 컴포넌트의 동일성 이해하기
목차
React에서의 리렌더링과 컴포넌트의 동일성 이해하기
React를 사용하다 보면 컴포넌트의 리렌더링과 관련된 궁금증이 생길 수 있습니다. 특히, 컴포넌트의 props나 state가 변경되지 않았는데도 리렌더링이 발생하거나, 반대로 변경되었는데도 리렌더링이 발생하지 않는 경우가 있습니다. 이번 글에서는 이러한 현상을 이해하기 위해 예제를 통해 React의 렌더링 동작을 살펴보겠습니다.
예제 코드 소개
아래는 간단한 React 애플리케이션입니다.
import React, { useState } from 'react';export default function App() {return (<><ParentWithChildren><ChildA /><ChildB /></ParentWithChildren><ParentWithoutChildren><ChildC /><ChildD /></ParentWithoutChildren></>);}function ParentWithChildren({ children }) {const [count, setCount] = useState(0);return (<><button onClick={() => setCount((prev) => prev + 1)}>Parent A Count: {count}</button>{children}</>);}function ChildA() {return <div>Child A</div>;}function ChildB() {return <div>Child B</div>;}function ParentWithoutChildren({ children }) {const [count, setCount] = useState(0);return (<><button onClick={() => setCount((prev) => prev + 1)}>Parent B Count: {count}</button>{/* children을 사용하지 않음 */}</>);}function ChildC() {return <div>Child C</div>;}function ChildD() {return <div>Child D</div>;}
동작 결과
- 처음 렌더링 시
App이 렌더링됩니다.ParentWithChildren,ChildA,ChildB가 렌더링됩니다.ParentWithoutChildren가 렌더링됩니다.ChildC,ChildD는 렌더링되지 않습니다.
ParentWithChildren의 버튼 클릭 시ParentWithChildren만 리렌더링됩니다.ChildA,ChildB는 리렌더링되지 않습니다.
ParentWithoutChildren의 버튼 클릭 시ParentWithoutChildren만 리렌더링됩니다.
궁금한 점과 그에 대한 해설
1. ParentWithChildren은 자식 컴포넌트들을 렌더링하는데, 왜 ParentWithoutChildren은 자식 컴포넌트들을 렌더링하지 않을까요?
답변:
ParentWithChildren컴포넌트는children을 받아서{children}으로 렌더링합니다. 따라서ChildA와ChildB가 화면에 나타납니다.ParentWithoutChildren컴포넌트는children을 받지만, 렌더링 함수 내에서 이를 사용하지 않습니다. 즉,{children}을 렌더링하지 않으므로ChildC와ChildD는 화면에 나타나지 않습니다.- 이처럼
children을 받아도 이를 렌더링에 사용하지 않으면 해당 자식 컴포넌트들은 렌더링되지 않습니다.