key를 사용하지 않으면❓
import React from 'react';
function ExampleComponent() {
const items = ['A', 'B', 'C'];
const listItems = items.map((item, index) =>
<li key={index}>
{item}
</li>
);
return (
<ul>
{listItems}
</ul>
);
}
export default ExampleComponent;
React 컴포넌트의 라이프 사이클은 컴포넌트가 생성, 업데이트, 소멸되는 일련의 단계를 말한다. 라이프 사이클 메소드는 이러한 단계에서 실행되는 함수들을 말하며, 클래스형 컴포넌트에서 주로 사용된다.
컴포넌트가 처음 렌더링될 때 발생하는 단계
컴포넌트가 업데이트될 때 발생하는 단계
컴포넌트가 DOM에서 제거될 때 발생하는 단계
컴포넌트 렌더링 중 에러가 발생할 때 호출되는 단계
// 실행했을 때의 순서: -1-, -2- ...
// 버튼 클릭 후의 순서: (1), (2) ...
import React, { Component } from 'react';
class LifeCycleExample extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
// 컴포넌트가 생성될 때 호출되는 생성자 메서드 -1-
console.log('Constructor called');
}
static getDerivedStateFromProps(props, state) {
// props로부터 state를 도출할 때 호출되는 메서드 -2- (1)
console.log('getDerivedStateFromProps called');
return null;
}
componentDidMount() {
// 컴포넌트가 마운트된 직후 호출되는 메서드 -4-
console.log('componentDidMount called');
}
shouldComponentUpdate(nextProps, nextState) {
// 컴포넌트 업데이트 여부를 결정할 때 호출되는 메서드 (2)
console.log('shouldComponentUpdate called');
return true;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
// 실제 DOM에 변화가 반영되기 직전 호출되는 메서드 (4)
console.log('getSnapshotBeforeUpdate called');
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
// 컴포넌트 업데이트 직후 호출되는 메서드 -6- (5)
console.log('componentDidUpdate called');
}
componentWillUnmount() {
// 컴포넌트가 언마운트되기 직전 호출되는 메서드 -5-
console.log('componentWillUnmount called');
}
handleClick = () => {
this.setState((prevState) => ({
count: prevState.count + 1,
}));
};
render() {
// 컴포넌트가 렌더링될 때 호출되는 메서드 -3- (3)
console.log('Render called');
return (
<div>
<h1>React Lifecycle Example</h1>
<p>Count: {this.state.count}</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
export default LifeCycleExample;
https://ko.legacy.reactjs.org/docs/react-component.html#the-component-lifecycle
최근에는 함수형 컴포넌트와 Hooks가 많이 사용되고 있다. 함수형 컴포넌트에서는 생명주기 메서드 대신 useEffect Hook을 사용하여 비슷한 작업을 수행할 수 있다.
useEffect는 컴포넌트가 마운트, 업데이트, 언마운트될 때 특정 작업을 수행할 수 있게 해준다.
예) useEffect의 두 번째 인자로 빈 배열을 전달하면 마운트 시에만 실행되는 것과 유사한 효과를 얻을 수 있다. 또한 의존성 배열을 통해 특정 state 변화에 반응하도록 할 수 있다.
이처럼 함수형 컴포넌트와 Hooks를 사용하면 생명주기 메서드를 직접 사용하지 않고도 컴포넌트의 상태 관리와 부수 효과 처리가 가능하다.
import React, { useState, useEffect } from 'react';
function LifeCycleHooksExample() {
const [count, setCount] = useState(0);
useEffect(() => {
// 컴포넌트가 마운트되거나 업데이트될 때 호출되는 useEffect
console.log('Component mounted or updated');
return () => {
// 컴포넌트가 언마운트될 때 호출되는 cleanup 함수
console.log('Component will unmount');
};
}, []);
useEffect(() => {
// count state가 변경될 때 호출되는 useEffect
console.log('Count state changed');
}, [count]);
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<h1>React Lifecycle Hooks Example</h1>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
export default LifeCycleHooksExample;