State Hook[React]

SnowCat·2023년 1월 17일
0

React - Hooks

목록 보기
2/7
post-thumbnail

※ 공식문서를 읽고 정리한 글입니다.

state 변수 선언

import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);
/*
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
*/
  • 함수 컴포넌트는 this를 가질 수 없기 때문에 this.state을 할당하는 대신 useState Hook을 직접 컴포넌트에 호출함
  • useState 안의 인자는 state의 초기값이 되며 반드시 객체일 필요는 없음
  • useState는 state 변수와 변수를 갱신할 수 있는 함수의 쌍을 반환함
    클래스에서 this.state.value, this.setState()를 반환하는 것과 유사
    예문처럼 배열 구조 분해 문법을 통해 값을 가져오면 됨
  • 여러개의 state가 필요한경우 여러쌍의 state를 선언하기만 하면 됨

State 가져오기, 갱신하기

<p>You clicked {count} times</p>
//<p>You clicked {this.state.count} times</p>
<button onClick={() => setCount(count + 1)}>
  Click me
</button>
/*
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
  Click me
</button>
*/
  • this 사용 없이 useState 선언시 사용했던 변수들을 사용하면 됨

출처:
https://ko.reactjs.org/docs/hooks-state.html

profile
냐아아아아아아아아앙

0개의 댓글