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] State

Last updated at Posted at 2024-11-27

環境

MacBook Pro (2.3 GHz 8コアIntel Core i9)
macOS 14.0(23A344)
Homebrew 4.3.8
gh 2.52.0

まとめ

Stateとは

コンポーネントのさまざまな視覚状態(例えば「初期状態」、「入力中状態」、「成功状態」)に対して表示したい UI を記述し、ユーザ入力に応じて state の変更をトリガします。

state の管理

つまり、
Stateは、Reactコンポーネントがその内部で持つ動的なデータを管理するためのオブジェクト
Stateは、ユーザーの操作や外部からのイベントによって変更され、Stateの変更はコンポーネントの再描画を引き起こし、Reactの「動的」なUI更新を可能にする

なぜStateが必要なのか

  1. 動的なUIの実現
  2. 状態(State)の管理

PropsとStateの違いは?

特徴 Props State
変更可能性 読み取り専用(不変) 変更可能(可変)
管理場所 親コンポーネント コンポーネント自身
データの流れ 親から子へ(単方向データフロー) コンポーネント内部のみ
役割 外部データの受け渡し 内部状態の管理
更新方法 親コンポーネントで値を変更 setStateuseStateを使って変更

ソースコードの前に

フォルダ構成

folda_structure
├── public/
│   ├── index.html
└── src/
│   ├── index.js(index.jsx)
│   └── App.js(App.jsx)

index.html

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>React App</title>
  </head>

  <body>
    <div id="root"></div>
  </body>
</html>

index.js

index.js
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

ソースコード(App.js)

Number

num: State変数
setNum: State変数を更新するための関数(更新関数)

App.jsx
import { useState } from "react";

export const App = () => {
  const [num, setNum] = useState(0);
  const onClickCountUp = () => {
    setNum(num + 1);
  };
  return (
    <>
      <button onclick={onClickCountUp}>カウントアップ</button>
      <p>{num}</p>
    </>
  );
};

動作

  • num + 1で、引数numを1つずつ増やす

Boolean

isShowFace: State変数
setIsShowFace: State変数を更新するための関数(更新関数)

App.jsx
import { useState } from "react";

export const App = () => {
  const [isShowFace, setIsShowFace] = useState(true);
  const onClickToggle = () => {
    setIsShowFace(!isShowFace);
  };
  return (
    <>
      <button onclick={onClickToggle}>on/off</button>
      {isShowFace && <p>\(^o^)/オワタ</p>}
    </>
  );
};

動作

  • !isShowFaceで、引数isShowFaceを反転させる
  • &&で、引数isShowFacetrueの時に\(^o^)/オワタが表示される

イメージ

Number

image.png

Boolean

image.png

Tips

  1. booleanを扱う変数には、is hasなどを変数の接頭語につける
    e.g. isShowFace

参考リンク

0
0
2

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?