Context API 를 사용한 전역 값 관리

김병화·2023년 1월 12일
0

Context API 사용 방법

  1. React.createContext()를 사용하여 새로운 Context를 만든다.
const UserDispatch = React.createContext(null);
  1. 전역 관리를 할 대상 컴포넌트를 Provider로 감싸준다.
    ProviderContext안에 들어있는 컴포넌트이다.
<UserDispatch.Provider value={dispatch}>...</UserDispatch.Provider>
  1. 대상 컴포넌트에 UserDispatch를 import 해주고, dispatch를 통해 조회하여 사용한다.
import React, { useContext } from 'react';
import { UserDispatch } from './App';

const User = React.memo(function User({ user }) {
  const dispatch = useContext(UserDispatch);

  return (
    <div>
      <b
        style={{
          cursor: 'pointer',
          color: user.active ? 'green' : 'black'
        }}
        onClick={() => {
          dispatch({ type: 'TOGGLE_USER', id: user.id });
        }}
      >
        {user.username}
      </b>
      &nbsp;
      <span>({user.email})</span>
      <button
        onClick={() => {
          dispatch({ type: 'REMOVE_USER', id: user.id });
        }}
      >
        삭제
      </button>
    </div>
  );
});

0개의 댓글