[React] React Hook - useContext

szlee·2023년 12월 5일
0

React

목록 보기
11/11

useContext

prop drilling 문제점

깊이가 너무 깊어지면 이 prop이 어떤 컴포넌트로부터 왔는지 파악이 어려워진다.
어떤 컴포넌트에서 오류가 발생할 경우 추적이 힘들어지니 대처가 늦다.
--> react context API 개념 등장.
useContext hook으로 쉽게 전역 데이터를 관리할 수 있게 되었다.



context API 필수 개념

  • createContext : context 생성
  • Consumer : context 변화 감지
  • Provider : 하위 컴포넌트로 context 전달

결론적으로 context는 중앙 관리소!




useContext를 사용하지 않았을 때

//App.jsx
import GrandMother from "./components/GrandMother";

export function App() {
  return <GrandMother />;
}

export default App;
// 1. GrandMother.jsx
import React from "react";
import Mother from "./Mother";

function GrandMother() {
  const houseName = "삐약삐약";
  const pocketMoney = 10000;

  return <Mother houseName={houseName} pocketMoney={pocketMoney} />;
}

export default GrandMother;
//2. Mother.jsx
import React from "react";
import Child from "./Child";

function Mother() {
  const houseName = "삐약삐약";
  const pocketMoney = 10000;

  return <Child houseName={houseName} pocketMoney={pocketMoney} />;
}

export default Mother;
//3. child.jsx
import React from "react";

function Child({ houseName, pocketMoney }) {
  const stressedWord = {
    color: "red",
    fontWeight: "900",
  };
  return (
    <div>
      나는 이 집안의 막내에요.
      <br />
      할머니가 우리 집 이름은 <span style={stressedWord}>{houseName}</span>
      라고 하셨어요.
      <br />
      게다가 용돈도 <span style={stressedWord}>{pocketMoney}</span>원만큼이나
      주셨답니다.
    </div>
  );
}

export default Child;

=> GrandMother 컴포넌트가 Child 컴포넌트에게 houseName과 pocketMoney를 전달해주기 위해 Mother 컴포넌트를 거칠 수 밖에 없었다.
만약 이 중간 컴포넌트가 100개라면 엄청 비효율적일 것이다.







useContext를 사용했을 때

context패키지 생성 > FamilyContext.js 생성 (context 생성)

//FamilyContext.js
import { createContext } from "react";

export const FamilyContext = createContext(null);
// 1. GrandMother.jsx
import React from "react";
import Mother from "./Mother";
import { FamilyContext } from "../context/FamilyContext";

function GrandMother() {
  const houseName = "삐약삐약";
  const pocketMoney = 10000;

  return (
    <FamilyContext.Provider value={{ houseName, pocketMoney }}>
      <Mother />
    </FamilyContext.Provider>
  );
}

export default GrandMother;
//2. Mother.jsx
import React from "react";
import Child from "./Child";

function Mother() {
  return <Child />;
}

export default Mother;
//3. child.jsx
import React, { useContext } from "react";
import { FamilyContext } from "../context/FamilyContext";

function Child({ houseName, pocketMoney }) {
  const stressedWord = {
    color: "red",
    fontWeight: "900",
  };
  
  const data = useContext(FamilyContext);
  console.log("data", data);
  
  return (
    <div>
      나는 이 집안의 막내에요.
      <br />
      할머니가 우리 집 이름은 <span style={stressedWord}>{data.houseName}</span>
      라고 하셨어요.
      <br />
      게다가 용돈도 <span style={stressedWord}>{data.pocketMoney}</span>원만큼이나
      주셨답니다.
    </div>
  );
}

export default Child;

이제 GrandMother -> Context(중앙관리소) -> Child순서로 잘 전달이 되었다.

주의사항

useContext를 사용할 때 Provider에서 제공한 value가 달라진다면 useContext를 사용하고 있는 모든 컴포넌트가 리렌더링된다. 따라서 value 부분을 항상 신경써주어야한다.

profile
🌱

0개의 댓글