Hooks?
Hooks는 리액트 16.8 버젼에 새롭게 추가된 함수로, 함수형 컴포넌트 내에서 state와 여러 lifecycle 기능들을 연동할 수 있게 돕는 메소드입니다. Hook은 일반적인 클래스형 함수에서는 작동하지 않고, 함수형 컴포넌트 내에서 동작하게 되며, react에 기본 탑재된 Hooks는 useState, useEffect, useRef, useReducer가 있으며, 자신만의 Hooks를 만들 수도 있습니다.
왜 사용할까요?
기존의 클래스형 함수로 컴포넌트를 작성할 때, state과 관련된 함수를 컴포넌트 간에 재사용하고 싶은 경우가 많이 생깁니다. Hook은 컴포넌트 트리에 새로운 컴포넌트를 추가하지 않고도 이것을 구현할 수 있게 해줍니다.
Hook 사용 규칙 2가지
- 최상위 레벨에서만 Hook을 호출해야 하며, 반복문, 조건문, 중첩된 함수 내에서는 실행해서는 안됩니다.
- React 함수형 컴포넌트 내에서만 호출해야 합니다.
useState
state를 쉽게 선언하고 할당, 재사용하기 위해 react에 기본 탑재된 Hooks입니다. 기본 구성은 아래와 같습니다.
const [state, setState] = useState(initialState);
- useState을 사용하여 첫 state의 기본 값을 지정할 수 있습니다.
- setState 함수는 state를 갱신할 때 사용하며, 새로운 state값을 받아서 컴포넌트를 리렌더링 합니다.
- 예시 코드
useState 예시 (클래스형 컴포넌트)
// 클래스형 컴포넌트
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
useState 예시 (함수형 컴포넌트)
import React, { useState } from 'react';
// 함수 컴포넌트
function Example() {
// 새로운 state 변수를 선언하고, count라 부르겠습니다.
const [count, setCount] = useState(0);
const [isModalActive, setIsModalActive] = useState(false);
// 안 좋은 예시
const [state, setState] = useState({
color: "red",
isActive: true,
name: "jt".
password: "sdaf"
})
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
<button onClick={() => setIsModalActive(!isModalActive)}>modal btn</button>
</div>
);
}
useEffect
기존 클래스형 컴포넌트의 componentDidMount와 componentDidUpdate와 같은 역할을 수행하는 Hooks입니다. 특정 조건을 만족할 경우 클로저 내의 명령을 수행합니다.
useEffect (컴디마, 컴디업 - 클래스형 컴포넌트)
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate(prevProps, prevState) {
if(prevState.count !== this.state.count){
document.title = `You clicked ${this.state.count} times`;
}
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
useEffect (함수형 컴포넌트)
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
// 브라우저 API를 이용하여 문서 타이틀을 업데이트합니다.
document.title = `You clicked ${count} times`; // CDM
}, []);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
- useEffect를 컴포넌트가 렌더링된 후 한 번만 실행 (컴디마와 같이) 하고 싶다면, useEffect의 두 번째 인자로 빈 배열을 선언해주면 됩니다.
- 특정 조건을 만족했을 때만 useEffect 하고 싶다면, 두번째 인자에 변화를 지켜볼 값을 선언해주면 됩니다.
1) 기존 컴디업 방식에서는
componentDidUpdate(prevProps, prevState) {
if (prevState,count !== this.state.count) {
document.titla = `You clicked ${this.state.count} times`;
}
}
2) useEffect를 사용한다면
useEffect(()=> {
document.title = `You clicked ${count} times`;
}, [count]); // count가 바뀔 때만 useEffect를 재실행합니다.
와 같이 변형할 수 있습니다.
연습
2주간 1차 프로젝트를 하며 모든 코드를 클래스형 컴포넌트로 작성했기 때문에, 클래스형 컴포넌트에 많이 익숙해진 상태입니다. 1차의 클래스형 컴포넌트 몇 개를 선정하여 함수형 + useState을 사용하는 코드로 변환해보는 연습을 해보고, 2차에서는 모든 코드를 위와 같은 방식으로 작성해보며 익숙해지는게 좋을 것 같습니다.
1 ) 여러 hooks를 살펴보고 기본 개념을 잡을 수 있는 사이트
Hooks.guide
hooks-guide.netlify.app
'프로그래밍' 카테고리의 다른 글
wecode (10/9) (0) | 2020.10.11 |
---|---|
React 10. Styled Components (0) | 2020.10.11 |
React 8. setState, this.props.children (0) | 2020.09.29 |
[Allstar] 컨버스 웹사이트 클론 팀프로젝트 후기 (0) | 2020.09.27 |
React 7 - Component Lifecycle (0) | 2020.09.26 |
댓글