FrontEnd/React
React의 Props Drilling
Bumang
2023. 10. 10. 09:25
Props를 자손으로 쭉쭉 내려다보내다보면 props가 어디까지 보내지는지 그 깊이를 알기 어려워지는 현상.
3~4개면 어떻게든 파악을 할텐데, depth가 15개 이상이면? props가 어떻게 보내지고 있는지 파악하는 것 자체가 시간이 든다.
import React from "react";
import "./styles.css";
export default function App() {
return (
<div className="App">
<FirstComponent content="Who needs me?" />
</div>
);
}
function FirstComponent({ content }) {
return (
<div>
<h3>I am the first component</h3>;
<SecondComponent content={content} />|
</div>
);
}
function SecondComponent({ content }) {
return (
<div>
<h3>I am the second component</h3>;
<ThirdComponent content={content} />
</div>
);
}
function ThirdComponent({ content }) {
return (
<div>
<h3>I am the third component</h3>;
<ComponentNeedingProps content={content} />
</div>
);
}
function ComponentNeedingProps({ content }) {
return <h3>{content}</h3>;
}
해결책
1. 전역 상태관리 라이브러리 사용
redux, MobX, recoil 등을 사용하여 해당 값이 필요한 컴포넌트에서 직접 불러서 사용할 수 있다.
2. 리액트 차일드를 통해 해결
리액트 차일드란?
어떤 컴포넌트 안의 구성요소가 동적으로 결정될 경우, children이란 props를 태그 사이에 쓸 수 있다.
해당 컴포넌트의 상위 컴포넌트에서 내용물을 결정할 수 있다.
const Category = ({ children }) => {
return <ul>{children}</ul>;
};
const App = () => (
<Category>
<li>First item.</li>
<li>Second item.</li>
<li>Another item.</li>
</Category>
);
이를 활용하면 depth가 얼마나 깊어지든 그 안의 요소를 파악할 수 있게 만들 수 있다.
import React from "react";
import "./styles.css";
export default function App() {
const content = "Who needs me?";
return (
<div className="App">
<FirstComponent>
<SecondComponent>
<ThirdComponent>
<ComponentNeedingProps content={content} />
</ThirdComponent>
</SecondComponent>
</FirstComponent>
</div>
);
}
function FirstComponent({ children }) {
return (
<div>
<h3>I am the first component</h3>;
{ children }
</div>
);
}
function SecondComponent({ children }) {
return (
<div>
<h3>I am the second component</h3>;
{children}
</div>
);
}
function ThirdComponent({ children }) {
return (
<div>
<h3>I am the third component</h3>
{children}
</div>
);
}
function ComponentNeedingProps({ content }) {
return <h3>{content}</h3>
}