Skip to Content
Suffering builds character

4. Hooks

React 초반에는 대부분의 컴포넌트를 아래와 같이 클래스 문법을 활용하여 작성하였으나, 코드가 다소 길어지고 복잡해지는 것을 줄이기 위해 요즘은 대부분 함수형 컴포넌트 형태로 작성

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

class-component.js
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 컴포넌트

functional-component.js
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) 사용한다는 의미로 네이밍됨

2-1. hook의 사용 제한 규칙

React hook은 함수형 컴포넌트 및 개발자가 직접 구현한 커스텀 훅에서만 사용 가능 일반적인 JS 함수에서는 사용 불가

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