LoginSignup
1
0

useStateとは

Posted at

useStateとは、ReactのHooksの一つで、状態を管理したいときに使う!
状態(state)とは、コンポーネントが内部で保持するデータであり、文字列、数値、真偽値、配列などさまざまな値を保持できる。

useStateは二つの値を持っており、一つが現在の状態の値を表す変数。
二つ目が状態を更新するための関数です。この関数を使って新しい状態の値をセットすることができる。

ボタンをクリックするとcountの値が1ずつ増加するプログラムを例にする。

.jsx
import { useState } from 'react';

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

  function handleIncrement() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleIncrement}>+1</button>
    </div>
  );
}

ここではuseStateの初期値に0を渡している。
そして、setCount関数を呼び出すことで、countの値がプラス1される。
また、handleIncrement関数はbuttonが押されるたびに呼ばれる。

このようにuseStateを使うことで状態を管理してあげることができる!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0