state:コンポーネントのメモリ

コンポーネントによっては、ユーザ操作の結果として画面上の表示内容を変更する必要があります。フォーム上でタイプすると入力欄が更新される、画像カルーセルで「次」をクリックすると表示される画像が変わる、「購入」をクリックすると買い物かごに商品が入る、といったものです。コンポーネントは、現在の入力値、現在の画像、ショッピングカートの状態といったものを「覚えておく」必要があります。React では、このようなコンポーネント固有のメモリのことを state と呼びます。

このページで学ぶこと

  • useState を使って state 変数を追加する方法
  • useState フックが返す 2 つの値
  • 複数の state 変数を追加する方法
  • state がローカルと呼ばれる理由

通常の変数ではうまくいかない例

以下は、彫刻の画像をレンダーするコンポーネントです。“Next” ボタンをクリックすると、index12 のように変わりながら次の彫刻が表示されて欲しいのですが、これは正しく動作しません(試してみてください)。

import { sculptureList } from './data.js';

export default function Gallery() {
  let index = 0;

  function handleClick() {
    index = index + 1;
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i> 
        by {sculpture.artist}
      </h2>
      <h3>  
        ({index + 1} of {sculptureList.length})
      </h3>
      <img 
        src={sculpture.url} 
        alt={sculpture.alt}
      />
      <p>
        {sculpture.description}
      </p>
    </>
  );
}

handleClick イベントハンドラは、ローカル変数 index を更新しています。しかし、以下の 2 つの理由により、目に見える変化が起きません。

  1. ローカル変数はレンダー間で保持されません。React がこのコンポーネントを次にレンダーするときは、まっさらな状態からレンダーします。過去にローカル変数を変更したことは考慮されません。
  2. ローカル変数の変更は、レンダーをトリガしません。新しいデータでコンポーネントを再度レンダーする必要があることに React は気づきません。

コンポーネントを新しいデータで更新するためには、次の 2 つのことが必要です。

  1. レンダー間でデータを保持する。
  2. 新しいデータでコンポーネントをレンダー(つまり再レンダー)するよう React に伝える

useState フックは、これら 2 つの機能を提供します。

  1. レンダー間でデータを保持する state 変数
  2. 変数を更新し、React がコンポーネントを再度レンダーするようにトリガする state セッタ関数

state 変数の追加

state 変数を追加するには、ファイルの先頭で React から useState をインポートします:

import { useState } from 'react';

次に、この行を:

let index = 0;

以下のように置き換えます:

const [index, setIndex] = useState(0);

index は state 変数であり、setIndex はセッタ関数です。

ここでの [] という構文は配列の分割代入と呼ばれるもので、配列から個々の値を読み取ることができます。useState から返される配列は常に正確に 2 個の要素を持っています。

これらは handleClick の中で以下のように動作します:

function handleClick() {
setIndex(index + 1);
}

これで、“Next” ボタンをクリックすると、現在の彫刻が切り替わるようになります:

import { useState } from 'react';
import { sculptureList } from './data.js';

export default function Gallery() {
  const [index, setIndex] = useState(0);

  function handleClick() {
    setIndex(index + 1);
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i> 
        by {sculpture.artist}
      </h2>
      <h3>  
        ({index + 1} of {sculptureList.length})
      </h3>
      <img 
        src={sculpture.url} 
        alt={sculpture.alt}
      />
      <p>
        {sculpture.description}
      </p>
    </>
  );
}

はじめてのフック

React では、useState やその他の use で始まる関数はフック (Hook) と呼ばれます。

フックは、React がレンダーされている間のみ利用可能な特別な関数です(この点については、次ページで詳しく説明します)。フックを使うことで、さまざまな React の機能に「接続 (hook into)」して使用することができます。

state はそれらの機能のうちのひとつですが、他のフックについても後で紹介します。

落とし穴

use で始まるフックは、コンポーネントのトップレベルまたはカスタムフック内でのみ呼び出すことができます。条件分岐、ループ、ネストされた関数の中でフックを呼び出すことはできません。フックは関数ですが、コンポーネントの要求に関する無条件の宣言を行うものだ、と捉えることが有用です。ファイルの先頭でモジュールを “import” するのと同様に、コンポーネントの先頭で React の機能を “use” するのです。

useState の構造

useState を呼び出すということは、このコンポーネントに何かを覚えさせるよう React に指示を出すということです:

const [index, setIndex] = useState(0);

この場合、React には index を覚えてもらいます。

補足

慣習的に、このペアは const [something, setSomething] のように命名します。自由に名前を付けることもできますが、慣習に従うことでプロジェクト間で理解しやすくなります。

useState に渡す唯一の引数は、state 変数の初期値です。この例では useState(0) とすることで index の初期値を 0 に設定しています。

コンポーネントがレンダーされるたびに、useState は以下の 2 つの値を含む配列を返します。

  1. 保存した値を保持している state 変数 (index)。
  2. state 変数を更新し、React にコンポーネントの再レンダーをトリガする state セッタ関数 (setIndex)。

以下は、これが実際にどのように動作するかを示しています。

const [index, setIndex] = useState(0);
  1. コンポーネントが初めてレンダーされるuseStateindex の初期値として 0 を渡したので、[0, setIndex] を返す。React は 0 が最新の state 値であることを覚える。
  2. state を更新する。ユーザがボタンをクリックすると、setIndex(index + 1) が呼び出される。現在 index0 なので、setIndex(1) になる。これにより、React は index1 になったことを覚え、再レンダーがトリガされる。
  3. コンポーネントの 2 回目のレンダー。React は再び useState(0) というコードに出会うが、React は index1 にセットしたことを覚えているので、代わりに [1, setIndex] を返す。
  4. 以降も続く。

コンポーネントで複数の state 変数を使う

1 つのコンポーネントは、いくつでも好きな型の state 変数を持つことができます。このコンポーネントは、数値型の index と、“Show details” をクリックすると切り替わるブーリアン型の showMore という、2 つの state 変数を持っています。

import { useState } from 'react';
import { sculptureList } from './data.js';

export default function Gallery() {
  const [index, setIndex] = useState(0);
  const [showMore, setShowMore] = useState(false);

  function handleNextClick() {
    setIndex(index + 1);
  }

  function handleMoreClick() {
    setShowMore(!showMore);
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleNextClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i> 
        by {sculpture.artist}
      </h2>
      <h3>  
        ({index + 1} of {sculptureList.length})
      </h3>
      <button onClick={handleMoreClick}>
        {showMore ? 'Hide' : 'Show'} details
      </button>
      {showMore && <p>{sculpture.description}</p>}
      <img 
        src={sculpture.url} 
        alt={sculpture.alt}
      />
    </>
  );
}

この例の indexshowMore のように state が互いに関連していない場合、複数の state 変数を持つのが良いでしょう。ただし、2 つの state 変数を一緒に更新することが多い場合は、それらを 1 つにまとめる方が簡単かもしれません。たとえば、多くのフィールドがあるフォームの場合、フィールドごとに state 変数を持つよりも、オブジェクトを保持する 1 つの state 変数を持つ方が便利です。詳しくは state 構造の選択を参照してください。

さらに深く知る

React はどの state を返すかをどのようにして知るのか?

useState の呼び出しには、どの state 変数を参照しているかに関する情報が含まれていないことに気付いたかもしれません。useState に「識別子」のようなものを渡さないのに、どの state 変数が返されるべきなのか、どのようにしてわかるのでしょうか。あなたの関数を解析するといった魔術的なものに頼っているのでしょうか? 答えはノーです。

そうではなく、簡潔な構文を実現するため、フックは同一コンポーネントの各レンダー間で同一の順番で呼び出されることに依存しています。上記のルール(「フックはトップレベルでのみ呼び出す」)に従っていれば、フックは常に同じ順序で呼び出されるので、これは実用上うまく機能します。また、リンタプラグインがほとんどの間違いをキャッチします。

内部的には、React はすべてのコンポーネントに対して state のペアの配列を保持しています。また、現在のペアインデックスも管理しており、レンダー前に 0 に設定されます。useState が呼び出されるたびに、React は次の状態ペアを提供し、インデックスをインクリメントします。このメカニズムについては、React Hooks: Not Magic, Just Arrays で詳しく説明されています。

以下の例は React を使っていませんがuseState が内部的にどのように機能するかの考え方がわかります。

let componentHooks = [];
let currentHookIndex = 0;

// How useState works inside React (simplified).
function useState(initialState) {
  let pair = componentHooks[currentHookIndex];
  if (pair) {
    // This is not the first render,
    // so the state pair already exists.
    // Return it and prepare for next Hook call.
    currentHookIndex++;
    return pair;
  }

  // This is the first time we're rendering,
  // so create a state pair and store it.
  pair = [initialState, setState];

  function setState(nextState) {
    // When the user requests a state change,
    // put the new value into the pair.
    pair[0] = nextState;
    updateDOM();
  }

  // Store the pair for future renders
  // and prepare for the next Hook call.
  componentHooks[currentHookIndex] = pair;
  currentHookIndex++;
  return pair;
}

function Gallery() {
  // Each useState() call will get the next pair.
  const [index, setIndex] = useState(0);
  const [showMore, setShowMore] = useState(false);

  function handleNextClick() {
    setIndex(index + 1);
  }

  function handleMoreClick() {
    setShowMore(!showMore);
  }

  let sculpture = sculptureList[index];
  // This example doesn't use React, so
  // return an output object instead of JSX.
  return {
    onNextClick: handleNextClick,
    onMoreClick: handleMoreClick,
    header: `${sculpture.name} by ${sculpture.artist}`,
    counter: `${index + 1} of ${sculptureList.length}`,
    more: `${showMore ? 'Hide' : 'Show'} details`,
    description: showMore ? sculpture.description : null,
    imageSrc: sculpture.url,
    imageAlt: sculpture.alt
  };
}

function updateDOM() {
  // Reset the current Hook index
  // before rendering the component.
  currentHookIndex = 0;
  let output = Gallery();

  // Update the DOM to match the output.
  // This is the part React does for you.
  nextButton.onclick = output.onNextClick;
  header.textContent = output.header;
  moreButton.onclick = output.onMoreClick;
  moreButton.textContent = output.more;
  image.src = output.imageSrc;
  image.alt = output.imageAlt;
  if (output.description !== null) {
    description.textContent = output.description;
    description.style.display = '';
  } else {
    description.style.display = 'none';
  }
}

let nextButton = document.getElementById('nextButton');
let header = document.getElementById('header');
let moreButton = document.getElementById('moreButton');
let description = document.getElementById('description');
let image = document.getElementById('image');
let sculptureList = [{
  name: 'Homenaje a la Neurocirugía',
  artist: 'Marta Colvin Andrade',
  description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
  url: 'https://i.imgur.com/Mx7dA2Y.jpg',
  alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'  
}, {
  name: 'Floralis Genérica',
  artist: 'Eduardo Catalano',
  description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
  url: 'https://i.imgur.com/ZF6s192m.jpg',
  alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
}, {
  name: 'Eternal Presence',
  artist: 'John Woodrow Wilson',
  description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
  url: 'https://i.imgur.com/aTtVpES.jpg',
  alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
}, {
  name: 'Moai',
  artist: 'Unknown Artist',
  description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
  url: 'https://i.imgur.com/RCwLEoQm.jpg',
  alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
}, {
  name: 'Blue Nana',
  artist: 'Niki de Saint Phalle',
  description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
  url: 'https://i.imgur.com/Sd1AgUOm.jpg',
  alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
}, {
  name: 'Ultimate Form',
  artist: 'Barbara Hepworth',
  description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
  url: 'https://i.imgur.com/2heNQDcm.jpg',
  alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
}, {
  name: 'Cavaliere',
  artist: 'Lamidi Olonade Fakeye',
  description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
  url: 'https://i.imgur.com/wIdGuZwm.png',
  alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
}, {
  name: 'Big Bellies',
  artist: 'Alina Szapocznikow',
  description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
  url: 'https://i.imgur.com/AlHTAdDm.jpg',
  alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
}, {
  name: 'Terracotta Army',
  artist: 'Unknown Artist',
  description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
  url: 'https://i.imgur.com/HMFmH6m.jpg',
  alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
}, {
  name: 'Lunar Landscape',
  artist: 'Louise Nevelson',
  description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
  url: 'https://i.imgur.com/rN7hY6om.jpg',
  alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
}, {
  name: 'Aureole',
  artist: 'Ranjani Shettar',
  description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
  url: 'https://i.imgur.com/okTpbHhm.jpg',
  alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
}, {
  name: 'Hippos',
  artist: 'Taipei Zoo',
  description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
  url: 'https://i.imgur.com/6o5Vuyu.jpg',
  alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
}];

// Make UI match the initial state.
updateDOM();

React を使用するためにこのことを理解する必要はありませんが、脳内モデルとして知っておくと役立つかもしれません。

state は独立しておりプライベート

state は画面上の個々のコンポーネントインスタンスに対してローカルです。言い換えると、同じコンポーネントを 2 回レンダーした場合、それぞれのコピーは完全に独立した state を有することになります! そのうちの 1 つを変更しても、もう 1 つには影響しません。

この例では、先ほどの Gallery コンポーネントが、そのロジックには変更を加えずに 2 回レンダーされています。それぞれのギャラリの中のボタンをクリックしてみてください。これらの state が独立していることが分かるでしょう。

import Gallery from './Gallery.js';

export default function Page() {
  return (
    <div className="Page">
      <Gallery />
      <Gallery />
    </div>
  );
}

これが state 変数と、モジュールのトップレベルで宣言する通常の変数との違いです。state は特定の関数呼び出しやコードの場所に紐付いているのではなく、画面上の特定の場所に対して「ローカル」になります。あなたが 2 つの <Gallery /> コンポーネントをレンダーしたので、それらの state は別々に保持されているのです。

また、Page コンポーネントは、Gallery の state の値も、そもそも state が存在するかどうかも「知らない」ということにも注目してください。props と違い、state はそれを宣言したコンポーネントに完全にプライベートなものです。親コンポーネントがそれを変更することはできません。このおかげで、任意のコンポーネントに state を追加したり削除したりしても、他のコンポーネントに影響を与えることはありません。

両方のギャラリで state を同期させたい場合はどうすればよいでしょうか? React での正解は、子コンポーネントから state を削除して、それらに最も近い共有の親に追加することです。ここからの数ページでは、1 つのコンポーネント内での state の管理に焦点を当てていますが、コンポーネント間での state 共有で改めてこのトピックに戻って解説します。

まとめ

  • レンダー間で情報を「記憶」しておく必要があるコンポーネントには、state 変数を使う。
  • state 変数は、useState フックを呼び出すことで宣言される。
  • フックは use から始まる特殊な関数であり、state などの React 機能に「接続」できる。
  • フックはインポートと似ており、無条件に呼び出す必要がある。useState などのフックの呼び出しは、コンポーネントのトップレベルか別のフックでのみ有効である。
  • useState フックは、現在の state とそれを更新する関数の組み合わせを返す。
  • 複数の state 変数を持つことができる。内部で React はそれらを呼び出し順を用いて対応付ける。
  • state はコンポーネントにプライベートなものである。2 つの場所でレンダーすると、それぞれのコピーが独立した state を得る。

最後の彫刻が表示されているときに “Next” を押すと、コードがクラッシュします。クラッシュを防ぐためにロジックを修正してください。そのためには、イベントハンドラに追加のロジックを追加するか、操作が不可能な場合はボタンを無効化しましょう。

クラッシュを修正できたら、“Previous” ボタンを追加して、ひとつ前の彫刻を表示するようにしてください。最初の彫刻でクラッシュしないようにしましょう。

import { useState } from 'react';
import { sculptureList } from './data.js';

export default function Gallery() {
  const [index, setIndex] = useState(0);
  const [showMore, setShowMore] = useState(false);

  function handleNextClick() {
    setIndex(index + 1);
  }

  function handleMoreClick() {
    setShowMore(!showMore);
  }

  let sculpture = sculptureList[index];
  return (
    <>
      <button onClick={handleNextClick}>
        Next
      </button>
      <h2>
        <i>{sculpture.name} </i> 
        by {sculpture.artist}
      </h2>
      <h3>  
        ({index + 1} of {sculptureList.length})
      </h3>
      <button onClick={handleMoreClick}>
        {showMore ? 'Hide' : 'Show'} details
      </button>
      {showMore && <p>{sculpture.description}</p>}
      <img 
        src={sculpture.url} 
        alt={sculpture.alt}
      />
    </>
  );
}