React Context API
안녕하세요! 오늘은 React에서 전역 상태 관리를 위해 자주 사용하는 Context API에 대해 알아보겠습니다. Context API는 컴포넌트 트리 전체에 데이터를 효율적으로 전달할 수 있는 방법을 제공합니다.
React Context API
1. Context API란?
Context API는 React에서 전역적으로 데이터를 공유할 수 있는 방법을 제공합니다. 이를 통해 중첩된 컴포넌트 간에 prop drilling 없이 데이터를 전달할 수 있습니다.
2. Context API 사용 예제
다음은 Context API를 사용하여 테마를 관리하는 간단한 예제입니다.
Step 1: Context 생성
먼저, Context를 생성합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
import React, { createContext, useState } from 'react';
export const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value=Jekyll::Drops::ThemeDrop>
{children}
</ThemeContext.Provider>
);
};
Step 2: Context 제공
ThemeProvider
를 사용하여 컴포넌트 트리 전체에 테마 데이터를 제공합니다.
1
2
3
4
5
6
7
8
9
10
11
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { ThemeProvider } from './ThemeContext';
ReactDOM.render(
<ThemeProvider>
<App />
</ThemeProvider>,
document.getElementById('root')
);
Step 3: Context 소비
useContext
훅을 사용하여 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
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
const ThemedButton = () => {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button
style=
onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
>
Toggle Theme
</button>
);
};
const App = () => {
return (
<div>
<h1>Context API Example</h1>
<ThemedButton />
</div>
);
};
export default App;
3. Context API의 장점
- 전역 상태 관리: Context API를 사용하면 애플리케이션의 전역 상태를 쉽게 관리할 수 있습니다.
- 간편한 데이터 전달: prop drilling 없이 컴포넌트 트리의 깊은 곳까지 데이터를 전달할 수 있습니다.
- 유연성: Context API는 다양한 유형의 데이터를 전달하는 데 유연하게 사용할 수 있습니다.
4. Context API의 단점
- 성능 문제: Context 데이터가 변경되면 해당 Context를 소비하는 모든 컴포넌트가 리렌더링될 수 있습니다.
- 복잡성 증가: 많은 Context를 사용하면 코드가 복잡해질 수 있습니다.
결론
React Context API는 전역 상태를 관리하고 중첩된 컴포넌트 간에 데이터를 효율적으로 전달하는 데 유용한 도구입니다. 올바르게 사용하면 prop drilling 문제를 해결하고, 애플리케이션의 상태 관리를 더욱 간편하게 할 수 있습니다. 그러나 성능 문제와 복잡성 증가를 방지하기 위해 신중하게 사용해야 합니다.
오늘도 제 글을 읽어주셔서 감사합니다. 다음 시간에 더 유익한 주제로 찾아뵙겠습니다.
This post is licensed under CC BY 4.0 by the author.