FE/React

[FE / REACT] Props Drilling

따봉치치 2023. 10. 10. 14:49
728x90

Props Drilling 

1. Props

  • 상위 컴포넌트가 하위 컴포넌트에 값을 전달할 때 사용(단방향 데이터 흐름)
  • 자식 컴포넌트에서 프로퍼티는 수정할 수 없음 (읽기 전용)

2. Props Drilling

props를 오로지 하위 컴포넌트로 전달하는 용도로만 쓰이는 컴포넌트들을 거치면서 React Component 트리의 한 부분에서 다른 부분으로 데이터를 전달하는 과정

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>;
}

content 를 App > First > Second > Third > ComponentNeedingProps 순으로 전달하여

ComponentNeedingProps 컴포넌트에서 해당 props를 사용하기 위해 전달하는 과정을 거치게 됨

➡️ props 전달이 10개 이상 컴포넌트를 거치게 되면 코드를 읽을 때 해당 props 추적이 어렵고 유지보수가 어려워지는 문제가 발생

➡️ 필요보다 많은 props를 전달하다가 컴포넌트를 분리하는 과정에서 필요 없는 props가 계속 남는 문제 발생

➡️ 필요보다 적은 props를 전달하면서 동시에 defaultProps를 과용한 결과로 필요한 props가 전달되지 않은 상황을 문제로 인지하지 못하는 상황 발생

 

Props Drilling 해결법

1. 전역 상태관리 라이브러리 사용

  • Recoil
  • Redux
  • Mobx
  • Context API

2. children 적극 사용

props.children은 주로 자식 컴포넌트 또는 html 엘리먼트가 어떻게 구성되어있는지 모르는데 화면에 표시해야 하는 경우 사용한다.

### Props Drilling 해결법

### 1. 전역 상태관리 라이브러리 사용

- Recoil
- Redux
- Mobx
- Context API

### 2. `children` 적극 사용

props.children은 주로 자식 컴포넌트 또는 html 엘리먼트가 어떻게 구성되어있는지 모르는데 화면에 표시해야 하는 경우 사용한다.

```jsx
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>
}
```
728x90