0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React hooksとuseState

Posted at

React hooksとは

React 16.8で追加された機能
関数コンポーネントで状態管理や副作用処理などのReactの機能を使えるようにする仕組み

useStateとは

関数コンポーネント内で状態管理するために使うもの

基本的な使い方

const [state, setState] = useState(initialValue);
  • state: 現在の状態の値
  • setState: 状態を更新する関数
  • initialValue: 状態の初期値(例えば 0, "", false など)

具体例

import { useState } from "react";

// +1ボタンを押すごとに、カウントが増える関数
function Counter() {
  // countの初期値を0に設定
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);  // countを1増やす
  };

  return (
    <div>
      <p>カウント: {count}</p>
      <button onClick={increment}>+1</button>
    </div>
  );
}

countの値は setCount(count + 1) を呼んだ直後にはすぐには更新されません(例えば、0の時に、+1ボタンを押しても、見かけは1となっていますが、本当のcountは0)。
仕組みなどを解説します。

Reactの画面表示と再レンダリングの仕組み

画面表示の動き

  1. setCount(count + 1);を呼びます
    → しかしcountの値は すぐには変わらないです
  2. Reactは「次のレンダリングが必要」と判断し、仮想DOM(実際のDOMの差分だけ変更したもの)を更新されます
  3. 新しいcountの値を持った新しい仮想DOMを作成します
  4. React が「変更点だけ」本物のDOMに適用(効率的に更新)します
  5. 画面が更新され、新しいcountが表示されます

レンダリングのタイミング

  • 初回レンダリング時
    • Counterコンポーネントが最初に表示されるとき、レンダリングされます
  • +1ボタンが押されたとき
    • 前回押されたときのcountの処理が実行されます

まとめ

useStateはReactの関数コンポーネント内で状態管理を行うためのフックで、状態を変更すると再レンダリングが発生します。状態の更新は即時反映されず、Reactが次のレンダリングで画面に反映します。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?