2-1. state

송한솔·2023년 4월 26일
0

ReactStudy

목록 보기
12/54
post-thumbnail

리액트에서 state는 컴포넌트 내에서 관리되는 데이터를 나타냅니다.
state는 컴포넌트의 동적인 특성을 구현하는 데 사용되며, 변경될 수 있는 데이터를 저장합니다.
state의 변경은 컴포넌트의 재렌더링을 발생시키기 때문에, 상태가 바뀌면 컴포넌트는 새로운 상태를 화면에 반영합니다.

클래스 컴포넌트에서의 state

클래스 컴포넌트에서는 생성자 함수 내부에서 this.state를 통해 초기 state 값을 설정합니다.
이후 this.setState() 메서드를 사용하여 state를 업데이트할 수 있습니다.

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

함수 컴포넌트에서의 state

함수 컴포넌트에서는 React의 Hooks를 사용하여 state를 관리합니다.
useState라는 Hook을 사용하여 state를 선언하고, 관리할 수 있습니다.

import React, { useState } from "react";

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

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
}

0개의 댓글