[React] useState hook 사용법

Patrick·2021년 5월 19일
0

React

목록 보기
3/3
post-thumbnail

리액트 훅을 사용하는 분들은 비교적 당연하게 useState를 사용하고 있을 것이다.
component를 나눠서 function을 이용하여 만드는 경우를 많이 볼 수 있다.

하지만 이는 몇 년전, 리액트 버전 16.8 이전까지만 해도 function component 안에서는 state를 사용 할 수 없었다.

그러나 이제는 React hook을 이용해서 사용 할 수 있게 되었으니 그 hook이 바로 useState이다!
( Hook은 function 밖에서 사용하지 못하며, 안에서만 사용해야한다! )

[ 버튼을 만들어서 숫자를 하나씩 올릴 수 있도록 만들어보자! ]

1. 불러오기
useState는 React의 함수인데 이를 사용 할 곳에서 우선 상단에 import를 해와야한다.
이 때 Javascript distructoring을 활용하여 가져온다.
그 모양은 아래와 같다.

import React, { useState } from 'react

2. 사용하기

const Counter = () => {
  const [count, setCount] = useState(0)
    
  return (
  	<div>
   	  <h1>Hook - useState</h1>
      <h2>{count}</h2>
   	</div>
    )
}

이와 같이 import를 한 후에 useState를 function 함수 안에서 사용할 수 있다.

console.log에 useState를 찍어보면 알겠지만, 이는 [undefiend, function] 으로 나올 것이다.
즉, count는 변수, setCount는 function을 나타낸다.
setCount는 변수를 컨트롤 하기 때문에 그 앞에 set이라고 통상적으로 붙여서 사용하게 된다.

그래서 전체적으로 나온 모양을 보면,

import React, { useState } from 'react'

const Counter = () => {

  const [count, setCount] = useState(0);

  const countUp = () => {
    setCount(count + 1);
  }

  const countDown = () => {
    setCount(count - 1);
  }

  const resetHandle = () => {
    setCount(0);
  }

    return (
    <div>
      <h1>Hook -useState</h1>
      <h2>{count}</h2>
      <button onClick={countUp}>+1</button>
      <button onClick={resetHandle}>RESET</button>
      <button onClick={countDown}>-1</button>
    </div>
  )
}

export default Counter

이처럼 사용 할 수 있는데, count 자체를 건드리지는 못한다.
이는 read-only로 사용이 되어지며 count를 변경하고 싶다면 setCount를 활용해서 count를 변경해야한다.


그런데 만약

const [count, setCount] = useState(0);
const [color, setColor] = useState(0);
const [number, setNumber] = useState(0);

이렇게 같은 useState(0)이 있다면 리액트는 어떻게 이를 구별할까?
리액트는 순서를 기억하게 된다.
즉, 첫 번째 useState는 count이고, 두 번째 useState는 color이고, 세 번째 useState는 number라는 순서를 기억하게 된다.

그러니 useState를 사용할 때는 top-level에 쓰인 순서대로 실행되도록 해야한다.


그렇다면 count는 현재값일까?
그것도 아니다.
예를 들어서

const Counter = () => {
    const [count, setCount] = useState(0);
    const countUp = () => {
    	setCount(count + 1);
    	setCount(count + 1);
    	setCount(count + 1);
    }
    
    return (
    	<div>
          <h1>{count}</h1>
          <button onClick={countUp}>+<button>
        </div>
    )
}

이렇게 하면 값은 3씩 올라갈까?
그렇지 않다.
3개의 count가 모두 0이므로 1씩만 올라간다.
그렇다면 어떻게 해야 3씩 올릴 수 있을까?
이 때는 함수를 이용하면 된다.

const Counter = () => {
    const [count, setCount] = useState(0);
    const countUp = () => {
	setCount(prevCount => prevCount + 1);
        setCount(prevCount => prevCount + 1);
        setCount(prevCount => prevCount + 1);
    }
    
    return (
    	<div>
          <h1>{count}</h1>
          <button onClick={countUp}>+<button>
        </div>
    )
}

이렇게 이전 값에 + 1을 해주게 되면 3씩 올라가게 만들 수 있을 것이다.


더불어 class에서는 Hooks를 사용 할 수 없다.

profile
예술을 사랑하는 개발자

0개의 댓글