App 컴포넌트에서 onToggle, onRemove 가 구현이 되어있고 이 함수들은 UserList 컴포넌트를 거쳐서 각 User 컴포넌트들에게 전달이 되고 있다.
여기서 UserList 컴포넌트의 경우에는 onToggle 과 onRemove 를 전달하기 위하여 중간 다리역할만 하고 있다.
function UserList({ users, onRemove, onToggle }) {
return (
<div>
{users.map(user => (
<User
user={user}
key={user.id}
onRemove={onRemove}
onToggle={onToggle}
/>
))}
</div>
);
}
UserList 에서는 해당 함수들을 직접 사용하는 일도 없다.
지금과 같이 특정 함수를 특정 컴포넌트를 거쳐서 원하는 컴포넌트에게 전달하는 작업은 리액트로 개발을 하다보면 자주 발생 할 수 있는 작업이다 위와 같이 컴포넌트 한개정도를 거쳐서 전달하는건 사실 그렇게 큰 불편함도 없지만, 만약 3~4개 이상의 컴포넌트를 거쳐서 전달을 해야 하는 일이 발생하게 된다면 이는 매우 번거로워질 것이다.
그럴 땐, 리액트의 Context API 와 이전 섹션에서 배웠던 dispatch 를 함께 사용하면 이러한 복잡한 구조를 해결 할 수 있다.
리액트의 Context API 를 사용하면, 프로젝트 안에서 전역적으로 사용 할 수 있는 값을 관리 할 수 있다.
Context API 를 사용해여 새로운 Context 를 만드는 방법을 알아보도록 한다.
Context 를 만들 땐 다음과 같이 React.createContext() 라는 함수를 사용한다.
const UserDispatch = React.createContext(null);
createContext 의 파라미터에는 Context 의 기본값을 설정할 수 있다. 여기서 설정하는 값은 Context 를 쓸 때 값을 따로 지정하지 않을 경우 사용되는 기본 값이다.
Context 를 만들면, Context 안에 Provider 라는 컴포넌트가 들어있는데 이 컴포넌트를 통하여 Context 의 값을 정할 수 있습니다. 이 컴포넌트를 사용할 때, value 라는 값을 설정해주면 된다.
<UserDispatch.Provider value={dispatch}>...</UserDispatch.Provider>
이렇게 설정해주고 나면 Provider 에 의하여 감싸진 컴포넌트 중 어디서든지 우리가 Context 의 값을 다른 곳에서 바로 조회해서 사용 할 수 있다.
우선 App 컴포넌트 에서 Context 를 만들고, 사용하고, 내보내는 작업을 해주도록한다.
// UserDispatch 라는 이름으로 내보내줍니다.
export const UserDispatch = React.createContext(null);
return (
<UserDispatch.Provider value={dispatch}>
<CreateUser
username={username}
email={email}
onChange={onChange}
onCreate={onCreate}
/>
<UserList
users={users}
onToggle={onToggle}
onRemove={onRemove}
/>
<div>활성사용자 수 : {count}</div>
</UserDispatch.Provider>
);
이제 UserList 컴포넌트에서 에서 onToggle 과 onRemove 와 관련된 코드들을 지워준다.
이제, User 컴포넌트에서 바로 dispatch 를 사용 할것인데, 그렇게 하기 위해서는 useContext 라는 Hook 을 사용해서 우리가 만든 UserDispatch Context 를 조회해야 한다.
import React, { useContext } from 'react';
// User 컴포넌트에서 바로 dispatch 를 사용 할건데요, 그렇게 하기 위해서는
// useContext 라는 Hook 을 사용해서 우리가 만든 UserDispatch Context 를 조회해야한다.
import { UserDispatch } from './App'
function UserList({ users }) {
return (
<div>
{users.map(user => (
<User
user={user}
key={user.id}
/>
))}
</div>
);
}
//------------------------------------------------------------------------------
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>
<span>({user.email})</span>
<button onClick={() => {
dispatch({
type: 'REMOVE_USER', id: user.id
});
}}>삭제</button>
</div>
);
}
useReducer 를 사용하면 이렇게 dispatch 를 Context API 를 사용해서 전역적으로 사용 할 수 있게 해주면 컴포넌트에게 함수를 전달해줘야 하는 상황에서 코드의 구조가 훨씬 깔끔해질 수 있다.
만약에 깊은 곳에 위치하는 컴포넌트에게 여러 컴포넌트를 거쳐서 함수를 전달해야 하는 일이 있다면 이렇게 Context API 를 사용하면 된다.