React의 생명주기 메서드 및 Hook에 대한 심층 분석: 리액트 고급 개발자 되기
2024-10-29 12:15:44React 생명주기 메서드 및 Hook 개요
React는 UI를 구축하는 가장 유명한 JavaScript 라이브러리 중 하나입니다. 이 라이브러리를 사용하면 선언적이고 효율적인 방법으로 사용자 인터페이스를 구축할 수 있습니다. React의 강력한 기능 중 하나는 컴포넌트의 생명주기를 관리하는 능력입니다. 이 글에서는 React의 생명주기 메서드와 Hooks에 대해 심도있게 살펴보겠습니다. 이는 효율적인 컴포넌트 개발에 필수적입니다.
생명주기 메서드란 무엇인가?
React의 생명주기는 컴포넌트가 DOM에 추가되고 제거되는 과정 전체를 말합니다. 이 과정에서 개발자는 특정 시점에 특정 작업을 수행할 수 있으며, 이는 성능 최적화는 물론 코드의 가독성 향상에도 큰 도움이 됩니다. React 클래스 컴포넌트에서 가장 많이 사용되는 생명주기 메서드에 대해 알아보겠습니다.
1. 마운팅 컴포넌트
-
constructor(props): 컴포넌트가 처음 인스턴스화될 때 호출됩니다. 주로 상태 초기화나 인스턴스 메서드 바인딩에 사용됩니다. -
componentDidMount(): 컴포넌트가 처음 DOM에 삽입된 후 호출됩니다. 서버에서 데이터를 페치하거나 구독을 설정하는 데 이상적입니다.
2. 업데이트 컴포넌트
componentDidUpdate(prevProps, prevState): 상태나 props의 변경으로 컴포넌트가 업데이트된 후 호출됩니다. 변경사항에 대응하여 작업을 수행하기에 적합합니다.
3. 언마운팅 컴포넌트
componentWillUnmount(): 컴포넌트가 DOM에서 제거되기 직전에 호출됩니다. 타이머나 구독을 취소하는 데 유용합니다.
4. 오류 처리
componentDidCatch(error, info): 자식 컴포넌트의 오류를 저장하고 처리합니다. 중앙 집중식 오류 처리에 적합합니다.
React Hooks 소개
Hooks는 함수형 컴포넌트에서도 클래스 컴포넌트의 기능을 사용할 수 있게 해주는 새로운 기능입니다. Hooks를 사용하면 컴포넌트 상태 및 생명주기를 클래스 없이도 관리할 수 있습니다.
1. useState()
- 상태를 함수형 컴포넌트에 추가할 때 사용됩니다. 현재 상태 값과 이를 업데이트하는 함수 배열을 반환합니다.
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
2. useEffect()
- 부수 효과(side effect)를 수행하는 Hook입니다.
componentDidMount,componentDidUpdate,componentWillUnmount의 기능을 결합합니다.
사용 예:
- 빈 배열 사용 (
[])- 의존성 배열이 비어 있는 경우 컴포넌트가 처음 마운트될 때만 부수 효과가 실행됩니다.
import React, { useState, useEffect } from 'react';
const FetchDataOnce = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
};
fetchData();
}, []);
return (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
- 의존성 배열 없이 사용
- 의존성 배열 없이 사용하면 컴포넌트가 리렌더링될 때마다 부수 효과가 실행됩니다.
import React, { useState, useEffect } from 'react';
const CountComponent = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log(`Count updated: ${count}`);
});
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
- 배열 의존성 사용
- 배열에 특정 상태나 props를 지정하면 해당 값이 변경될 때만 부수 효과가 실행됩니다.
import React, { useState, useEffect } from 'react';
const DependOnCount = () => {
const [count, setCount] = useState(0);
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const response = await fetch(`https://api.example.com/data/${count}`);
const result = await response.json();
setData(result);
};
fetchData();
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
};
3. useContext()
- 전역 상태나 테마 같은 공통 데이터를 깊은 컴포넌트 트리 전체에 전달할 때 사용합니다. prop drilling을 피할 수 있어 코드가 깔끔해집니다.
Example: 테마 컨텍스트
- 테마 컨텍스트 생성
import React, { createContext, useContext, useState } from 'react';
// Create a Theme Context
const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
const toggleTheme = () => {
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
- 컨텍스트 소비
const ThemedComponent = () => {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<div className={`theme-${theme}`}>
<h1>{theme === 'light' ? 'Light Theme' : 'Dark Theme'}</h1>
<button onClick={toggleTheme}>
Switch to {theme === 'light' ? 'Dark' : 'Light'} Theme
</button>
</div>
);
};
- 애플리케이션에 테마 프로바이더 적용
const App = () => {
return (
<ThemeProvider>
<ThemedComponent />
{/* Other components can also access the ThemeContext here */}
</ThemeProvider>
);
};
export default App;
결론
React의 생명주기 메서드와 Hooks는 React 애플리케이션 개발에 있어 강력한 도구입니다. 이들의 이해와 활용은 효율적이고 반응성 있는 사용자 인터페이스를 구축하는 데 필수적입니다. 클래스 컴포넌트의 생명주기 메서드와 기능 컴포넌트의 Hooks를 통해 상태 관리 및 컴포넌트 행동을 제어해 보세요.