[React] Props Drilling

DongHyeon Jung·2022년 10월 26일
0

React

목록 보기
13/15
post-thumbnail

Props Drilling

props drilling이란?

일반적으로 props를 통해 컴포넌트 끼리 데이터를 전달한다
Prop Drilling  가장 아래 컴포넌트만 데이터가 필요할 때에도 모든 상위 컴포넌트들도 단계를 거쳐야 한다는 것을 말한다

왜 문제일까?

아래의 예시 코드를 살펴보면
가장 최상위의 App 컴포넌트에서 setCount라는 useState 함수를 전달할때
App -> DisplayCount -> Button 컴포넌트로 props가 전달되는데, 문제는 아무런 기능을 하지 않는 컴포넌트 또한 props를 전달해주어야 한다는 것이다
즉, 복잡한 컴포넌트들 사이에서 이러한 과정을 반복한다면 유지보수에 많은 어려움을 겪게 된다
또한 props를 수정하고 싶을 때 자식 하나씩 추적해야 한다면 비효율적이게 될 것이다

Example

App.js

function App() {
	const [count, setCount] = useState(0);

	return (
		<div className="App">
		<DisplayCount count={count} setCount={setCount} />
		</div>
		);
}

export default App;

DisplayCount.js

function DisplayCount(props) { 
	return ( 
		<div> count: {props.count} 
			<Button setCount={props.setCount} /> 
		</div> 
	); 
}

Button.js

function Button(props) {
	return (
		<button onClick={() => props.setCount(count => count + 1)}>
			Increase Count
		</button>
	);
}

Reference

https://youtu.be/LwvXVEHS638

0개의 댓글