[React] useState 를 통해 컴포넌트에서 바뀌는 값 관리하기

2022. 7. 28. 14:49React

리액트 16.8 이전 버전에서는 함수형 컴포넌트에서는 상태를 관리할 수 없었는데,

리액트 16.8 에서 Hooks 라는 기능이 도입되면서 함수형 컴포넌트에서도 상태를 관리할 수 있게 되었다.

이번에는 useState 라는 함수를 사용해보게 되는데, 이게 바로 리액트의 Hooks 중 하나이다.

 

Class형 컴포넌트의 길어지는 코드 길이 문제, 중복 코드, 가독성 문제 등등을 해결하기 위해 등장함

 

1. useState

컴포넌트에서 동적인 값을 상태(state)라고 부른다.

리액트에 useState 라는 함수가 있는데, 이것을 사용하면 컴포넌트에서 상태를 관리 할 수 있다.

이 코드는 리액트 패키지에서 useState 라는 함수를 불러와준다.

useState 를 사용 할 때에는 상태의 기본값을 파라미터로 넣어서 호출해준다.

이 함수를 호출해주면 배열이 반환되는데, 여기서 첫번째 원소는 현재 상태, 두번째 원소는 Setter 함수이다.

const [state, setState] = useState(initialState);

const [count, setCount] = useState(0);
// 원래는 위와 같이 해야하지만, 배열 비구조화 할당을 통하여 각 원소를 추출해줬다.
const numberState = useState(0);
const number = numberState[0];
const setNumber = numberState[1];

 

 

Counter.js

import React, {useState} from 'react'
// useState : 상태를 사용하겠다 라고 추가적인 메소드를 import해줘야한다

const Counter = () => {
    // count : 0번쨰 인덱스 count는 상태 값으로 사용됨.
    // setCount : 1번째 인덱스 상태변화 함수
    // (0) 초깃값 0

    // 리액트는 컴포넌트 state가 바뀌면 리렌더됨. 
    console.log("counter 호출");

    const [count, setCount] = useState(0)
    const onIncrease = () => {
        setCount(count + 1);
    }
    const onDecrease = () => {
        setCount(count - 1);
    }

    const [count2, setCount2] = useState(0)
    const onIncrease2 = () => {
        setCount2(count2 + 1);
    }
    const onDecrease2 = () => {
        setCount2(count2 - 1);
    }

    return (
        <div>
            <h2>{ count }</h2>
            <button onClick={ onIncrease } >+</button>
            <button onClick={ onDecrease } >-</button>

            <h2>{ count2 }</h2>
            <button onClick={ onIncrease2 } >+</button>
            <button onClick={ onDecrease2 } >-</button>
        </div>
    )
}

export default Counter

 

App.js

import './App.css';
import Counter from './Counter';

function App() {
  return (
    <div className="App">
      <Counter></Counter>
    </div>
  );
}

export default App;

함수를 만들고, button 의 onClick 으로 각 함수를 연결했다.

리액트에서 엘리먼트에 이벤트를 설정해줄때에는 on이벤트이름={실행하고싶은함수} 형태로 설정해주어야 한다.

여기서 주의해야하는 점은, 함수형태를 넣어주어야 하지, 함수를 다음과 같이 실행하시면 안된다.

onClick={onIncrease()}

 

 

 

참고

 

7. useState 를 통해 컴포넌트에서 바뀌는 값 관리하기 · GitBook

7. useState 를 통해 컴포넌트에서 바뀌는 값 관리하기 지금까지 우리가 리액트 컴포넌트를 만들 때는, 동적인 부분이 하나도 없었습니다. 값이 바뀌는 일이 없었죠. 이번에는 컴포넌트에서 보여줘

react.vlpt.us

 

Hooks API Reference – React

A JavaScript library for building user interfaces

ko.reactjs.org

'React' 카테고리의 다른 글

[React] Console.log 두 번  (0) 2022.07.29
[React] Dom 조작하기 - useRef  (0) 2022.07.29
[React] 사용자 입력 처리하기  (0) 2022.07.29
[React] props  (0) 2022.07.28
[React] 리액트를 사용하는 이유  (0) 2022.07.22