개발하는지호 2023. 12. 19. 20:20

1. 클래스형 컴포넌트와 함수형 컴포넌트

 

과거에는 대부분의 컴포넌트를 아래와 같이 클래스 문법을 활용하여 작성하였으나, 코드가 다소 길어지고 복잡해지는 것을 줄이기 위해 최근에는 함수형 컴포넌트로 작성하는 방식을 선호하고 있다.

 

class 방식으로 작성된  Counter 컴포넌트

const { useState, memo, Component } = React;

class Counter extends Component {
	constructor(props) {
		super(props);
		// 초기 상태 설정
		this.state = {
			count: 0
		};
	}

	// 카운터 증가 함수
	increment = () => {
		this.setState(prevState => ({
			count: prevState.count + 1
		}));
	};

	// 카운터 감소 함수
	decrement = () => {
		this.setState(prevState => ({
			count: prevState.count - 1
		}));
	};
	render() {
		return (
			<div>
				<h1>{this.state.count}</h1>
				<button onClick={this.increment}>Increase</button>
				<button onClick={this.decrement}>Decrease</button>
			</div>
		);
	}
}

 

 

함수형 방시으로 작성된 Counter 컴포넌트

const { useState } = React;
	
	const Counter = () => {
		const [count, setCount] = useState(0);
		const clickHandler = () => count += 1;
		return (
			<div>
				<p>{count}</p>
				<button onClick={clickHandler}>Click me</button>
			</div>
		)
	}
	const root = ReactDOM.createRoot(document.getElementById('root'));
	root.render(<Counter />);

 

 

2. React Hooks

 

클래스형 컴포넌트에서만 사용이 가능했던 상태(state) 를 관리하거나 Ref 등을 함수형 컴포넌트에서도 사용할 수 있도록 등장한 함수로, React에서 제공하는 내장 함수라고 볼 수 있다.

 

이러한 Hook은 클래스에서 제공되는 기능을 가져와서 (hooking) 사용한다는 의미로 네이밍된다.

function add(a, b) {
	useEffect(() => {...}, []); // x
}

 

 

*hook의 종류

useState

useEffect

useReducer

 

이 셋을 사용할 때 렌더링이 다시 된다.