React의 children prop에 대해

FE_Sujin·2024년 3월 20일
0

React

목록 보기
2/8
post-thumbnail

children prop이란

children prop

  • 부모 컴포넌트 내부에서 자식 컴포넌트 정보에 접근할 수 있게 하는 prop

아래 예시 코드에서 ParentComponentChildComponent를 감싸고 있다.

즉, ParentComponentChildComponent의 부모 컴포넌트이므로, ParentComponentChildComponent의 정보에 children이라는 이름의 props로 접근할 수 있다.

// JSX
<ParentComponent>
	<ChildComponent />
</ParentComponent>
// ParentComponent 컴포넌트
const ParentComponent = (props) => {
	return <>{props.children}</>
	
	// 만약 props.children값을 리턴해주지 않으면 화면 상에 ChildComponent 출력 안됨
}

두 컴포넌트는 부모-자식 관계를 가지는데, 부모 컴포넌트의 state값이 바뀌면 부모 컴포넌트가 리렌더링 되면서 자식 컴포넌트도 리렌더링 된다.

따라서 위와 같은 구조에서 ParentComponent의 state값이 바뀌는 등의 리렌더링 작업이 이루어지면, ChildComponent도 리렌더링이 된다는 뜻이다.

이때 ChildComponent에는 변경된 요소가 없는데도 부모 컴포넌트인 ParentComponent 때문에 리렌더링 된다면 이는 비효율적인 작업이라 볼 수 있다.

이 부분을 최적화하기 위해 React.memo를 써줄 수 있다.

  • React.memo 사용한 예시
const ChildComponent = React.memo(() => {
  console.log("ChildComponent is rendering!");
  return <div>Hello World!</div>;
});

또는

const ChildMemo = React.memo(ChildComponent)

const ParentComponent = () =>{
	console.log("ParentComponent is rendering!");
    const [toggle, setToggle] = useState(false);
	return <div>
    	<ChildMemo/>
        <button onClick={()=>{setToggle(!toggle)}}>
        	re-render
        </button>
    </div>
}

React.memo 없이도 props.children은 리렌더링 되지 않는다

하지만 React.memo를 사용하지 않고도, 자식 컴포넌트의 리렌더링을 막아줄 수 있다.

import React, { useState } from 'react';

const ChildComponent = () =>{
	console.log("ChildComponent is rendering!");
	return <div>Hello World!</div>
}

const ParentComponent = ({ children }) =>{
	console.log("ParentComponent is rendering!");
    const [toggle, setToggle] = useState(false);
	return <div>
 		{children}  // <ChildComponent /> 대신 children props를 렌더링 해줌
        <button onClick={()=>{setToggle(!toggle)}}>
        	re-render
        </button>
    </div>
}

const Container =() =>{
	return <div>
    	<ParentComponent>
        	<ChildComponent/>
        </ParentComponent>
    </div>
}

아까와는 다르게 ParentComponent의 JSX에 <ChildComponent />를 배치하지 않고, children prop을 return하고 있다.

이 상태에서는 React.memo 없이도 ParentComponent가 리렌더링 될 때, ChildComponent는 리렌더링 되지 않는다.


왜 React의 부모 컴포넌트가 리렌더링 될 때 props.children은 리렌더링이 일어나지 않을까?

JSX의 각 태그는 html을 닮았을 뿐 전부 react element를 반환하는 javascript 코드이다.

즉 아래의 두 코드는 모두 동일한 표현이다.

<Child/>
React.createElement(Child,null,null)  // 첫번째 argument는 타입이며, 두번째, 세번째 argument는 각각 porps와 children

React.creatElement는 주어진 arguments를 기반으로 react element를 새롭게 생성해 반환하고,

이렇게 생성된 react element들은 화면에 어떻게 나타내어질지 정보를 담고 있는 object형태로 존재한다.

react element는 값이 변하지 않는 상수이며, element의 변경은 곧 새로운 element를 생성한다는 것을 의미한다.

즉, Parent의 children은 애초에 object 형태인 상수로 전달받았기 때문에 렌더링 이전과 비교해서 값이 달라질리 없고, 따라서 re-render 되지도 않는 것이다.


참고

profile
안녕하세요 :)

0개의 댓글

관련 채용 정보