-
2020/11/23 - TIL(React Hook)Develop/React 2020. 11. 23. 15:48
React Hook
Hook은 리액트 v16.8부터 도입된 기능으로, 클래스 컴포넌트가 아닌 함수 컴포넌트에서도 State와 Lifecycle 메소드를 사용할 수 있도록 해준다.
State
useState를 사용하여 state를 함수 컴포넌트 안에서 사용할 수 있다.
import React, { useState } from 'react'; function Example() { // ... }
state 선언하기
클래스 컴포넌트는 constructor안에서 this.state를 {count : 0}이런 식으로 선언하였지만
class Example extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; }
함수형 컴포넌트는 this를 가질 수 없기 때문에 this.state를 할당하거나 읽을 수 없다. 대신 useState Hook을 사용할 수 있다.
import React, { useState } from 'react'; function Example() { // 새로운 state 변수를 선언하고, 이것을 count라 부르겠습니다. const [count, setCount] = useState(0);
useState는 클래스 컴포넌트의 this.state가 제공하는 기능과 동일하다. 일반적으로 변수는 함수가 끝날 때 사라지지만, state변수는 사라지지 않는다.
배열 안의 첫 번째 요소는 state의 이름이고, 두 번째 요소는 this.setState()와 동일한 state의 상태를 변경할 수 있는 함수이다.
useState()의 인자로 넘겨주는 값은 state의 초기값이다. 함수 컴포넌트의 state는 클래스 컴포넌트와 달리 객체일 필요 없고, 숫자 타입과 문자 타입을 가질 수 있다.
state 가져오기
클래스 컴포넌트는 count를 가져오기 위해 this.state.count를 사용하지만
<p>You clicked {this.state.count} times</p>
함수 컴포는트는 count 변수를 직접 사용할 수 있다.
<p>You clicked {count} times</p>
state update
클래스 컴포넌트는 count를 갱신하기 위해 this.setState를 사용하지만
<button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me </button>
함수 컴포넌트는 setCount 함수와 count 변수를 가지고 있으므로 this를 호출하지 않아도 된다.
<button onClick={() => setCount(count + 1)}> Click me </button>
Effect Hook
Effect Hook을 사용하여 함수 컴포넌트에서 side effect를 수행할 수 있다.
import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); // componentDidMount, componentDidUpdate와 같은 방식으로 useEffect(() => { // 브라우저 API를 이용하여 문서 타이틀을 업데이트합니다. document.title = `You clicked ${count} times`; },[someState]); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
userEffect는 클래스 컴포넌트의 생명주기 메소드인 componentDidMount, componentDidUpdate, componentWillUnmout가 합쳐진 것으로 생각할 수 있다.
render가 호출될 때마다(componentDidMount, componentDidUpdate) useEffect가 실행되며, 두 번째 인자를 통하여 특정한 state가 update 되었을 때만 effect가 실행되도록 설정이 가능하다.
두 번째 인자에 빈 배열을 넘기게 되면 최초(componentDidMount)에만 실행이 되도록 할 수 있다.
componentWillUnmount는 effect 함수의 return 값이 있는 경우 hook의 cleanUp함수로 인식하고 다음 effect가 실행되기 전에 실행해 준다.
useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; });
리액트는 컴포넌트가 마운트 해제되는 때에 clean-up을 실행한다.
Hook 규칙
- 최상위(at the Top Level)에서만 Hook을 호출해야 한다.
반복문, 조건문 혹은 중첩된 함수 내에서 Hook을 호출할 수 없다. - React 함수 내에서만 Hook을 호출해야 한다.
일반적인 Javascript 함수에서는 호출이 불가능하다.
'Develop > React' 카테고리의 다른 글
2020/11/27 - TIL(React-Router) (0) 2020.11.27 2020/11/25 - TIL(Redux 개념 정리) (0) 2020.11.25 2020/11/19 - TIL(React 공식문서 파헤치기3) (0) 2020.11.19 2020/11/19 - TIL(React 공식문서 파헤치기2) (0) 2020.11.19 2020/11/19 - TIL(React 공식문서 파헤치기 1) (0) 2020.11.19 - 최상위(at the Top Level)에서만 Hook을 호출해야 한다.