1 minute read

学んだこと

State

State とは?

  • それぞれのコンポーネントの状態のことを指す
  • 分割代入で State を定義する場合は
    • [State名, Stateを更新するときの関数名] = useState(初期値)で設定する。

実装例

  • State を使う場合は、import を行う必要がある。

import { ColorfulMessage } from './components/ColorfulMessage';
import { useState } from 'react';
export const App = () => {
  const [num, setNum] = useState(0);
  const onClickButton = () => {
    setNum(num + 1);
  };
  const contentStyleA = { color: 'blue', fontSize: '18px' };
  const contentStyleB = { color: 'green', fontSize: '18px' };
  return (
    <>
      <h1 style={contentStyleA}>こんにちは!</h1>
      <ColorfulMessage color="blue">お元気ですか?</ColorfulMessage>
      <ColorfulMessage color="green">元気です!</ColorfulMessage>
      <button onClick={onClickButton}>カウントアップ</button>
      <p>{num}</p>
    </>
  );
};

注意点

  • State は更新関数が呼ばれるタイミングで更新されない。
    • 同じ関数が複数呼ばれている場合は、まとめて State のセット処理が実行される。(バッチ処理みたいなことを行う。)
    • 下記の処理の場合はこのような処理になっている。
      • setNum(0 + 1)
      • setNum(0 + 1)
    • 結果 num に設定されるのは 1 になる。
import { ColorfulMessage } from './components/ColorfulMessage';
import { useState } from 'react';
export const App = () => {
  const [num, setNum] = useState(0);
  const onClickButton = () => {
    // 実行すると+1しかされなかった。
    setNum(num + 1);
    setNum(num + 1);
  };
  const contentStyleA = { color: 'blue', fontSize: '18px' };
  const contentStyleB = { color: 'green', fontSize: '18px' };
  return (
    <>
      <h1 style={contentStyleA}>こんにちは!</h1>
      <ColorfulMessage color="blue">お元気ですか?</ColorfulMessage>
      <ColorfulMessage color="green">元気です!</ColorfulMessage>
      <button onClick={onClickButton}>カウントアップ</button>
      <p>{num}</p>
    </>
  );
};
  • 現在の State の値を見て State を変更したい場合は、以下の様に処理を行うと実現できる。
    • stateセット関数((引数) => ...)で実現できる。
    • 引数に state の値を取得することができ、戻り値で state の値をセットしている。
import { ColorfulMessage } from './components/ColorfulMessage';
import { useState } from 'react';
export const App = () => {
  const [num, setNum] = useState(0);
  const onClickButton = () => {
    setNum((prev) => prev + 1);
    setNum((prev) => prev + 1);
  };
  const contentStyleA = { color: 'blue', fontSize: '18px' };
  const contentStyleB = { color: 'green', fontSize: '18px' };
  return (
    <>
      <h1 style={contentStyleA}>こんにちは!</h1>
      <ColorfulMessage color="blue">お元気ですか?</ColorfulMessage>
      <ColorfulMessage color="green">元気です!</ColorfulMessage>
      <button onClick={onClickButton}>カウントアップ</button>
      <p>{num}</p>
    </>
  );
};

Tags:

Updated: