TK-NOTE

技術的なことや趣味、読んだ本についての感想などを投稿してきます。

useStateについて知る

Cover Image for useStateについて知る
React

useStateとは何か?

useState はReact hooks のひとつ。useStateを使うことで状態の管理ができるようになります。
useStateは第一引数には管理したい状態の初期値を設定します。
返却値としては、管理したい状態とその状態を変更するための関数の配列が返ります。分割代入で取得するのが一般的です。

const [状態, 状態を変更する関数] = useState(初期値);
const [count, setCount] = useState(0);


クラスコンポーネントにおける状態管理

クラスコンポーネントでも状態管理をすることができます。
以下はクラスコンポーネントを使って状態管理する例です。

import React from "react";

class SampleWithClassComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }
  render() {
    return (
      <div>
        <p>current count is {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          {" "}
          +1{" "}
        </button>
        <button onClick={() => this.setState({ count: this.state.count - 1 })}>
          {" "}
          -1{" "}
        </button>
      </div>
    );
  }
}

export default SampleWithClassComponent;


useStateを使った状態管理

上記処理を関数コンポーネントでuseStateを使用して書き換えてみます。
行数が少なく、すっきりすることがわかると思います。

import React, { useState } from "react";

const SampleWithArrowComponent = () => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>current count is {count}</p>
      <button onClick={() => setCount(count + 1)}>+1</button>
      <button onClick={() => setCount(count - 1)}>
        -1
      </button>
    </div>
  );
};
export default SampleWithArrowComponent;