Context API를 사용해서 전역 값 관리하기

G-NOTE·2021년 6월 29일
0

React

목록 보기
13/27

  • value 값이 컴포넌트 F, J에서 보여주고 있고, 이 값을 변화시키는 이벤트는 컴포넌트 G에서 발생한다.
  • 이 상황에서 value 값과 handleSetValue 함수를 하위 컴포넌트에 props로 전달한다.
    - value : Root -> A -> B -> F
    • value : Root -> H -> J
      - handleSetValue 값 : Root -> A -> B -> E -> G
  • 프로젝트의 규모가 커지면 컴포넌트의 깊이가 깊어질 수 있고 다루는 데이터의 양이 많아질 수 있기 때문에 유지보수가 어려워진다.

예제

ContextSample.js

import React, { createContext, useContext } from "react";

function Child({ text }) {
  return <div>안녕하세요? {text}</div>;
}

function Parent({ text }) {
  return <Child text={text} />;
}

function GrandParent({ text }) {
  return <Parent text={text} />;
}

function ContextSample() {
  return <GrandParent text="Good" />;
}

export default ContextSample;

*Context 적용

import React, { createContext, useContext } from "react";

// context에서 사용할 기본값 설정
const MyContext = createContext("defaultValue");

function Child() {
  const text = useContext(MyContext);
  return <div>안녕하세요? {text}</div>;
}

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

function GrandParent() {
  return <Parent />;
}

function ContextSample() {
  return (
    <MyContext.Provider value="Good">
      <GrandParent />
    </MyContext.Provider>
  );
}

export default ContextSample;
  • useContext : context에 있는 값을 읽어서 사용할 수 있게 해주는 React 내장 Hook
  • 만약 MyContext의 값을 지정해주고 싶다면 context를 사용하는 최상단(ContextSample)에서 context 내부에 있는 Provider 컴포넌트를 사용해야 한다.
  • context를 만들 때 createContext 함수를 사용해서 인수를 전달하여 Provider 컴포넌트를 사용하지 않을 때 기본값이 된다.
  • Provider의 value로 전달한 값이 context의 값이 된다.

실습

  • 기존에는 userList를 onToggle이나 onRemove 이벤트가 user 컴포넌트에 전달하기 위해 userList를 거쳐야 한다는 불필요한 액션이 있었다.
    - 해결방법 1. context를 통해 onToggle, onRemove를 직접 넣는다.
    • 해결방법 2. dispatch만 넣는 방법
  • UserDispatch라는 context를 만들고 기본값은 필요없기 때문에 null을 넣는다.
  • UserDispatch의 value는 useReducer로 받은 dispatch로 지정한다.
  • 기존 App.js에 있던 onToggle, onRemove를 제거한다.
  • UserList에 있던 onToggle, onRemove도 제거하고 User 내부에서 onRemove, onToggle을 바로 만든다. (useContext 훅 활용)
  • App.js에서 UserDispatch를 import해서 context를 만들어 dispatch를 사용할 수 있도록 한다.

참조

https://velopert.com/3606

profile
FE Developer

0개의 댓글