component 간 state 공유

혜빈·2024년 7월 3일
0

REACT 보충개념

목록 보기
29/48

각각의 React 컴포넌트 파일에서 동일한 이름의 state를 사용해도 괜찮을까?

YES.

  • 각 컴포넌트는 독립적인 스코프를 가지고 있어서 각 컴포넌트 내에서만 유효함
    따라서 사용 가능

두 컴포넌트 간에 state를 공유해야 하는 경우라면?

  1. 상위 컴포넌트에서 state 관리 (Lifting State Up)
  • 공유가 필요한 state를 두 컴포넌트의 공통 부모 컴포넌트로 이동시킴
  • 이 state를 변경하는 함수도 부모 컴포넌트에서 정의함
  • state와 state 변경 함수를 자식 컴포넌트들에게 porps로 전달함

function Parent() {
  const [sharedCount, setSharedCount] = useState(0);

  return (
    <>
      <ChildA count={sharedCount} setCount={setSharedCount} />
      <ChildB count={sharedCount} setCount={setSharedCount} />
    </>
  );
}
  1. Context API 사용
  • 여러 컴포넌트에서 공유해야 하는 데이터를 위해 사용함
  • 주로 전역 상태나 테마, 인증 정보 등을 관리할 때 유용함

const CountContext = React.createContext();

function CountProvider({ children }) {
  const [count, setCount] = useState(0);
  return (
    <CountContext.Provider value={{ count, setCount }}>
      {children}
    </CountContext.Provider>
  );
}

// 사용하는 컴포넌트에서
function ChildComponent() {
  const { count, setCount } = useContext(CountContext);
  // ...
}
  1. 상태 관리 라이브러리 사용
  • 복잡한 애플리케이션에서 더 체계적인 상태 관리가 필요할 때 사용

  • Redux, Recoil, MobX 등이 있음

  • Redux 예시 코드


// store 생성
const store = createStore(rootReducer);

// Provider로 앱 전체를 감싸기
<Provider store={store}>
  <App />
</Provider>

// 컴포넌트에서 사용
function Component() {
  const count = useSelector(state => state.count);
  const dispatch = useDispatch();
  // ...
}

  • 작은 규모의 앱에서는 props drilling이나 Context API로 충분할 수 있지만,
    큰 규모의 복잡한 앱에서는 상태관리 라이브러리가 더 적합함
profile
최강 개발자를 꿈꾸는 병아리

0개의 댓글