React Hooks-useState
이 블로그 글은 리액트를 한번쯤 다뤄보고 보면 훨씬! 이해가 잘 될 수 있을 글입니다
리액트를 classComponent와 functionalComponent를 사용해서 열심히 앱을 만들었다! 그러나 올해 2월 리액트에서 새로운 기술을 빼꼼 꺼내놓았다.
그 이름하야 리액트~훅스!
React-Hooks란?
리액트 훅스는 react version 16.8에서 처음으로 선보인 채!신!기!술!이다.
이 리액트 훅스를 이용하면 이제 더 이상 Stateful Component를 만들때도 class Component를 생성하지 않아도 된다.
이말인 즉슨, functional Component에서 state를 관리할 수 있다는 말이다!
우리가 보통 클래스로 컴포넌트를 선언한다면 아래와 같은 형식으로 작성할겁니다.
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>
);
}
}React-Hooks-useState를 사용해보자
import React, { useState } from "react";
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}천천히 차이점을 살펴봅니다.
//1line
import React, { useState } from "react";useState를 react에서 구조분해할당으로 가져온다.
//4line
const [count, setCount] = useState(0);구조분해할당이 아주 많이 보이니까 꼭 es6를 공부해야한다! 옵션이 아니라 필수다!
잡설 그만 하고, const로 선언하는 구조분해할당 어레이를 살펴보면 첫번째 인자 count가 우리가 평소 클래스 컴포넌트에서 this.state.count라고 접근했던 그 count다!
두번째 인자 setCount는 this.setState({count:0}) 이런 형식으로 setState와 비슷한 함수다. 그러나 일반 setState는 모든 state에 접근가능하지만, ReactHooks의 setCount는 count라는 값만 변경할 수 있다.
간단하게 정리하자면 이렇게 바뀌었다.
| classComponents | functionalComponents | |
|---|---|---|
| state + setState(…) | => | useState(…) |
| [this.state.something, this.setState({ something: ??? })] | 단순 비교를 위한 예시 | [something, setSomething()] |
React-Hooks-useState 실제 적용
그러면 이제 실제로 적용하는 부분을 살펴볼 차례다!
//8~11line
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>ReactHooks에서 적용된 코드를 살펴보면 8번째 줄에 실제 비구조화할당으로 선언하였던 count를 그대로 가져와서 사용할 수 있다. ClassComponent의 경우 this.state.count로 가져오거나, 별도로 const { count } = this.state; 처럼 비구조화할당을 해주어야 count로 사용 할 수 있다.
굉장히 편리해졌쥬~?
그 아래는 count를 1 증가시키는 기능을 가진 버튼이 있다. 그 안에 onClick Function 을 살펴보자
ClassComponent에서 count 증가식을 만들면! 아래를 보자
<button onClick={() => this.setState({ count: this.state.count + 1 })}>확실히 짧고 간결하다. this를 이용한 바인딩도 하지 않아도 된다.
근데…사실 굳이 리액트 훅을 안써도 된다. ###하지만 Hooks는 너무나 편하다 ###가장 눈에 보이는 가장 큰 것은
class를 사용하기위해 reactComponent를 가져오지 않아도 된다는 것
useState의 설명은 여기까지다!