Context API

현우.·2024년 9월 11일
0

react

목록 보기
4/6
post-thumbnail

prop을 통한 정보전달

  • 일반적으로 부모 컴포넌트에서 자식 컴포넌트로 props을 통해 정보를 전달한다.
  • 이러한 과정이 깊어지면 props을 컴포넌트 사이로 여러번 전달해야하는데 이를 prop drilling(속성 내리 꽂기)라고하며 굉장히 불편하다.
  • 이를 해결하기위한 방법으로 컴포넌트 합성이 있지만 이는 프로젝트가 커질수록 부모 컴포넌트가 비대해지는 단점이 있다.

Context를 사용한 정보전달

  • 부모 컴포넌트가 props를 통해 명시적으로 전달하지 않고도 트리의 아래 컴포넌트에 정보를 제공할 수 있다.
  • 즉 앱의 모든 컴포넌트에서 사용할 수 있는 데이터(state)를 전달할 때 유용하다.

Context API 사용법

  1. createContext 메서드를 사용하여 context 생성한다.
  2. 생성한 context를 대상 컴포넌트에 값을 전달하기 위해서 Provider로 대상 컴포넌트를 감싼다.
  3. Provider의 프로퍼티인 value에 전달할 데이터를 넣는다.
  4. Provider의 value에 담은 데이터를 전달 할 때는, 2가지 방식으로 전달이 가능하다.
    • 1)Consumer 컴포넌트 사용
    • 2)useContext라는 훅을 이용

예제 코드

// context 생성
export const CartContext= createContext({
    //  자동 완성을 도와주는 기능
    items:[],
    addItemToCart : ()=>{},
    updateCartItemQuantity: ()=>{},
});

export default function App(){
  ...
  // 전달할 데이터
 const ctxValue = {
      items: shoppingCartState.items,
      addItemToCart : handleAddItemToCart,
      updateCartItemQuantity:handleUpdateCartItemQuantity,
    }
  return (
    <CartContext.Provider value={ctxValue}>  
      <Header/>
      <Shop>
      {DUMMY_PRODUCTS.map((product) => (
          <li key={product.id}>
            <Product {...product} />
          </li>
        ))}
      </Shop>
    </CartContext.Provider>
  );
}

4-1)

export default function Header() {
  ...
  return (
    <CartContext.Consumer>
    {(cartCtx)=>{
 
 	 const cartQuantity = cartCtx.items.length;
     if (cartQuantity > 0) {
        modalActions = (
          <>
            <button>Close</button>
            <button>Checkout</button>
          </>
        );
      }
    	return (
        <CartModal
        ref={modal}
        title="Your Cart"
        actions={modalActions}
      />
      <header id="main-header">
        <div id="main-title">
          <img src="logo.png" alt="Elegant model" />
          <h1>Elegant Context</h1>
        </div>
        <p>
          <button onClick={handleOpenCartClick}>Cart ({cartQuantity})</button>
        </p>
      </header>
	);
    </CartContext.Consumer>
  )
}

4-2)

export default function Header() {
  const {items} =useContext(CartContext);					   const cartQuantity = items.length;

    if (cartQuantity > 0) {
    modalActions = (
      <>
        <button>Close</button>
        <button>Checkout</button>
      </>
    );
  }
  ...
  return (
    <>
      <CartModal
        ref={modal}
        title="Your Cart"
        actions={modalActions}
      />
      <header id="main-header">
        <div id="main-title">
          <img src="logo.png" alt="Elegant model" />
          <h1>Elegant Context</h1>
        </div>
        <p>
          <button onClick={handleOpenCartClick}>Cart ({cartQuantity})</button>
        </p>
      </header>
    </>
  );
}
profile
학습 기록.

0개의 댓글