Post

Context API

React Context API에 대한 이해

Context API란?

React Context API는 컴포넌트 트리 전체에 걸쳐 전역적인 데이터를 공유할 수 있게 해주는 기능입니다. 주로 테마, 사용자 정보, 애플리케이션 설정 등과 같이 여러 컴포넌트에서 공통으로 필요로 하는 데이터를 관리할 때 유용합니다. Context API를 사용하면 일일이 props를 전달하지 않고도 필요한 데이터를 원하는 컴포넌트에서 사용할 수 있습니다.

Context API 사용법

1. Context 생성

Context를 생성하려면 React.createContext 메서드를 사용합니다. 이 메서드는 기본값을 인수로 받아 Context 객체를 반환합니다.

1
2
3
import React from 'react';

const MyContext = React.createContext(defaultValue);

2. Provider 설정

Provider 컴포넌트는 Context를 제공하는 역할을 합니다. Provider는 value prop을 받아 이 값을 하위 컴포넌트에게 전달합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
import React, { useState } from 'react';

const MyContext = React.createContext();

function MyProvider({ children }) {
  const [value, setValue] = useState('default value');

  return (
    <MyContext.Provider value={value}>
      {children}
    </MyContext.Provider>
  );
}

3. Consumer 사용

Consumer 컴포넌트는 Context를 구독(subscribe)하여 해당 Context의 값을 사용할 수 있게 해줍니다. Consumer는 함수 컴포넌트 내에서 사용되며, 함수의 인수로 Context의 현재 값을 받습니다.

1
2
3
4
5
6
7
8
9
10
11
import React from 'react';
import MyContext from './MyContext';

function MyComponent() {
  return (
    <MyContext.Consumer>
      {value => <div>Context Value: {value}</div>}
    </MyContext.Consumer>
  );
}

4. useContext Hook

함수형 컴포넌트에서 Context를 더 쉽게 사용할 수 있도록 React는 useContext Hook을 제공합니다. 이 Hook을 사용하면 Consumer 컴포넌트를 사용하지 않고도 Context의 값을 직접 사용할 수 있습니다.

1
2
3
4
5
6
7
8
9
import React, { useContext } from 'react';
import MyContext from './MyContext';

function MyComponent() {
  const value = useContext(MyContext);

  return <div>Context Value: {value}</div>;
}

Context API의 주요 기능

1. 전역 상태 관리

Context API를 사용하면 애플리케이션의 전역 상태를 쉽게 관리할 수 있습니다. 이를 통해 props drilling을 피하고, 컴포넌트 트리의 깊숙한 곳에서도 필요한 데이터를 사용할 수 있습니다.

2. 다중 Context 사용

React는 여러 Context를 동시에 사용할 수 있도록 지원합니다. 이를 통해 다양한 종류의 전역 상태를 독립적으로 관리할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import React, { createContext, useContext } from 'react';

// 두 개의 Context 생성
const ThemeContext = createContext('light');
const UserContext = createContext({ name: 'Guest' });

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <UserContext.Provider value=>
        <Toolbar />
      </UserContext.Provider>
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  return (
    <div>
      <ThemeButton />
      <UserProfile />
    </div>
  );
}

function ThemeButton() {
  const theme = useContext(ThemeContext);
  return <button>{theme} mode</button>;
}

function UserProfile() {
  const user = useContext(UserContext);
  return <div>User: {user.name}</div>;
}

마무리

React Context API는 전역 상태를 관리하고 여러 컴포넌트에서 공통 데이터를 공유할 수 있게 해주는 강력한 도구입니다. 이를 통해 props drilling을 피하고, 애플리케이션의 상태를 효율적으로 관리할 수 있습니다.

감사합니다.

This post is licensed under CC BY 4.0 by the author.