LoginSignup
5
5

More than 3 years have passed since last update.

【React】Functional ComponentにStateを持たせる方法【FC】

Posted at

TL;DL

ReactのFunctional ComponentにStateを持たせる方法がスマートだったので紹介します。
Class Componentに存在していたconstructorだのthisだの、鬱陶しいコードが不要になります。
公式ドキュメントに詳しく書かれています。
https://ja.reactjs.org/docs/hooks-state.html

コードと解説

公式ドキュメントから持ってきたコードを用いて解説します。

function Example() {
  // countというstateを定義します。
  // 値を更新する場合はsetCount関数を使います。
  // 例えば、countの値を3にする場合setCount(3)と書きます。
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      {/* 
     クリックされたときにsetCount(count+1)が
     実行されるように関数が渡されています。
   */}
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

useStateは型の指定や、初期値の指定ができます。

// textはstring型になります。
// 初期値は"abc"になります。
const [text, setText] = useState<string>("abc");

参考

5
5
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
5
5