개발자
류준열
Props 변화와 리렌더링은 무관하다
Props 변경이 리렌더링을 일으킨다는 글들이 많다.
부모컴포넌트가 리렌더링되면 자식컴포넌트도 리렌더링된다.
샌드박스에서 Props를 고정시켜보았다.
Props를 고정시켰을때에도 자식컴포넌트는 리렌더링된다.
Props와 무관하게 부모컴포넌트가 리렌더링되면 자식컴포넌트도 리렌더링된다.
그러므로 리렌더링을 막기 위해 Props에 메모이제이션을 하는 등의 일은 무의미하다.
const Parent = () => {
const memoValue = useMemo(()=>({value}),[])
return <Child value={memoValue}/> // Child는 리렌더링된다.
}
자식컴포넌트의 Props변화가 없을때 리렌더링을 막고 싶다면 자식컴포넌트를 memo로 감싸주어야 한다.
const memoChild = memo(Child)
const Parent = () => {
return <memoChild />
}
동료분과의 토론
동료들에게 위 내용을 공유했는데, 한 분께서 다음 반론을 하셨다.
부모컴포넌트가 리렌더링되면 자식컴포넌트는 무조건 리렌더링되는데, 이게 부모컴포넌트의 리렌더링때문인지 props 변화때문인지 증명할 수 없기 때문에 props변화와 리렌더링이 무관함을 확인 할 수 없다.
아래 3가지를 만족하는 코드를 작성하여 확인했다.
- 리렌더링되지 않는 부모컴포넌트
- 자식컴포넌트로 내려주는 Props는 변경되어야 함.
- 이때 Props가 변경되어도 자식컴포넌트는 리렌더링되지 않아야 함.
ref를 이용하여 부모컴포넌트를 렌더링 시키지 않고 자식컴포넌트로 내려주는 Props만 변경했을때 자식컴포넌트는 렌더링되지 않았다.
import { useRef } from "react";
const App = () => {
const textRef = useRef("Hello");
return (
<>
<p>
Code to check whether a child component re-renders due to the parent
component or props.
<br />
</p>
<button
onClick={() => {
// console.log("before change textRef.current:", textRef.current);
textRef.current = "Hello World";
// console.log("after change textRef.current:", textRef.current);
}}
>
Change props
</button>
<br />
Parents Component: {textRef.current}
<Child textRef={textRef} />
<hr />
</>
);
};
const Child = ({ textRef }: any) => {
console.log("Child render");
return (
<p>
Open Console and click button
<br />
<button
onClick={() => {
console.log("This is Props", textRef);
}}
>
A button to check the props of the child component.{" "}
</button>
<div>{textRef.current}</div>
</p>
);
};
export default App;