본문 바로가기

React/Velopert's React

[React] Study #21 | Context API를 사용한 전역 값 관리

이전 #20 까지 공부했던 챕터에서 까지, 특정 함수를 특정 컴포넌트를 거쳐서 원하는 컴포넌트에게 전달해주었다.

컴포넌트 한개 정도를 거쳐서 전달하는 것은 사실 큰 불편함은 없지만,

만약 3~4개 이상의 컴포넌트를 거쳐서 전달을 해야하는 일이 발생한다면 매우 번거로울 것..!

 

그럴 땐, 리액트의 Context API와 이전 #20에서 배운 dispatch를 사용하면 복잡한 구조를 해결!

 


💡 Context API?

  • 프로젝트 안에서 전역적으로 사용할 수 있는 값을 관리할 수 있다.
  • 꼭 상태를 가리키지 않아도 된다. (값!)
  • 이 값은 함수일 수도, 외부 라이브러리 인스턴스 일 수도 있고, 심지어 DOM일 수도 있다.

 

1️⃣ Context 만들기

const UserDispatch = React.createContext(null);

React.createContext() 사용!

파라미터로는 Context의 기본값 설정

 

💡Provider?

Context를 만들면 Provider라는 컴포넌트가 들어있는데, 이 컴포넌트를 통해 Context의 값을 정할 수 있다.

Provider 컴포넌트를 사용할 때, value 라는 값을 설정해주면 됨!

<UserDispatch.Provider value={dispatch}> ... </UserDispatch.Provider>

이렇게 Provider에 의해 감싸진 컴포넌트 중 어디서든지 우리가 Context의 값을 다른 곳에서 바로 조회해서 사용할 수 있다.

 

 

위의 코드들을 사용하면, 우리가 UserDispatch라는 Context를 만들어서, 어디서든지 dispatch를 꺼내 쓸 수 있도록 준비를 해주게 된것이다.

 

내보내는 작업의 코드인

export const UserDispatch = React.createContext(null);

은 나중에 사용하고 싶을 때 아래와 같이 불러와서 사용할 수 있다.

import { UserDispatch } from './App';

 

 

2️⃣이제 특정 컴포넌트에서 바로 dispatch를 사용하는 코드를 만들어보자.

useContext라는 Hook을 사용해서 우리가 만든 UserDispatch Context를 조회해야한다.

import React, { useContext } from 'react';
import { UserDispatch } from './App';

const User = React.memo(function User({ user }) {

  // useContext Hook을 사용하여 UserDispatch에서 dispatch 가져오기
  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>
  );
});

function UserList({ users }) {
  return (
    <div>
      {users.map(user => (
        <User user={user} key={user.id} />
      ))}
    </div>
  );
}

export default React.memo(UserList);

이렇게 Context API를 사용해서 dispatch를 어디서든지 조회해서 사용해 줄 수 있게 해주면 코드의 구조가 훨씬 깔끔해질 수 있다.

 


이로써 useState를 사용하는 것과 useReducer을 사용하는 것의 큰 차이를 발견했다!

useReducer를 사용하면 이렇게 dispatch를 ContextAPI를 사용해서 전역적으로 사용해줄 수 있다

-> 컴포넌트에게 함수를 전달해줘야 하는 상황에서 코드의 구조가 훨씬 깔끔해질 수 있다.

 


Reference

벨로퍼트의 모던 리액트