ステート:コンポーネントの記憶
コンポーネントは、インタラクションの結果として画面上の表示を変更する必要があることがよくあります。フォームへの入力は入力フィールドを更新し、イメージカルーセルの「次へ」をクリックすると表示される画像が変更され、「購入」をクリックすると商品がショッピングカートに入れられる必要があります。コンポーネントは、現在の入力値、現在の画像、ショッピングカートなど、「物事を記憶」する必要があります。Reactでは、このようなコンポーネント固有のメモリをステートと呼びます。
学習内容
useState
フックを使用したステート変数の追加方法useState
フックが返す値のペア- 複数のステート変数を追加する方法
- ステートがローカルと呼ばれる理由
通常の変数が十分でない場合
これは彫刻画像をレンダリングするコンポーネントです。「次へ」ボタンをクリックすると、index
を1
、次に2
などに変更して、次の彫刻を表示する必要があります。ただし、これは機能しません(試してみてください!)
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つのことがその変更を可視化するのを妨げています
- ローカル変数はレンダー間で永続化しません。Reactがこのコンポーネントを2回目にレンダリングする場合、最初からレンダリングします。ローカル変数への変更は考慮しません。
- ローカル変数への変更はレンダーをトリガーしません。Reactは、新しいデータでコンポーネントを再度レンダリングする必要があることを認識しません。
新しいデータでコンポーネントを更新するには、次の2つのことが必要です
- レンダー間でデータを保持します。
- 新しいデータでコンポーネントをレンダリングするようにReactをトリガーします(再レンダリング)。
useState
フックは、これら2つのものを提供します
- ステート変数:レンダー間でデータを保持します。
- ステートセッター関数:変数を更新し、Reactにコンポーネントを再度レンダリングするようにトリガーします。
ステート変数の追加
ステート変数を追加するには、ファイルの先頭でReactからuseState
をインポートします
import { useState } from 'react';
次に、この行を
let index = 0;
次のように置き換えます
const [index, setIndex] = useState(0);
index
はステート変数であり、setIndex
はセッター関数です。
ここでの
[
と]
の構文は、配列の分割代入と呼ばれ、配列から値を読み取ることができます。useState
によって返される配列には、常に正確に2つのアイテムがあります。
handleClick
でどのように連携するかは次のとおりです
function handleClick() {
setIndex(index + 1);
}
これで、「次へ」ボタンをクリックすると、現在の彫刻が切り替わります
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
" で始まる他の関数はすべて、フックと呼ばれます。
フック は、React が レンダリング している間(これについては次のページで詳しく説明します)にのみ利用可能な特別な関数です。これにより、さまざまな React の機能に「フック」することができます。
ステートはその機能の1つにすぎませんが、他のフックについては後ほど紹介します。
useState
の構造
useState
を呼び出すと、このコンポーネントに何かを記憶させたいことを React に伝えます。
const [index, setIndex] = useState(0);
この場合、React に index
を記憶させたいとします。
useState
の唯一の引数は、ステート変数の初期値です。この例では、index
の初期値は useState(0)
で 0
に設定されています。
コンポーネントがレンダリングされるたびに、useState
は2つの値を含む配列を返します。
- 保存した値を持つステート変数(
index
)。 - ステート変数を更新し、React にコンポーネントを再度レンダリングさせるステートセッター関数(
setIndex
)。
その動作を次に示します。
const [index, setIndex] = useState(0);
- コンポーネントが初めてレンダリングされます。
index
の初期値としてuseState
に0
を渡したので、[0, setIndex]
が返されます。React は、0
が最新のステート値であることを記憶します。 - ステートを更新します。ユーザーがボタンをクリックすると、
setIndex(index + 1)
が呼び出されます。index
は0
なので、setIndex(1)
となります。これにより、React はindex
が1
になったことを記憶し、別のレンダリングをトリガーします。 - コンポーネントの2回目のレンダリング。React はまだ
useState(0)
を見ていますが、index
を1
に設定したことを React が記憶しているため、代わりに[1, setIndex]
が返されます。 - 以降も同様です。
コンポーネントに複数のステート変数を与える
1つのコンポーネントに、必要な数のステート変数を必要なタイプで持つことができます。このコンポーネントには、2つのステート変数があります。1つは数値の index
で、もう1つはブール値の showMore
で、「詳細を表示」をクリックすると切り替わります。
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} /> </> ); }
この例の index
と showMore
のように、ステートが関連していない場合は、複数のステート変数を持つことをお勧めします。ただし、2つのステート変数を一緒に変更することが多い場合は、それらを1つに結合する方が簡単な場合があります。たとえば、多くのフィールドを持つフォームがある場合、フィールドごとにステート変数を持つよりも、オブジェクトを保持する単一のステート変数を持つ方が便利です。詳細については、ステート構造の選択をお読みください。
詳細
useState
の呼び出しが、どのステート変数を参照するかについての情報をまったく受け取っていないことに気付いたかもしれません。 useState
に渡される「識別子」がないため、返すステート変数をどのように認識するのでしょうか。関数の解析のような魔法に頼っているのでしょうか?答えはノーです。
代わりに、簡潔な構文を可能にするために、Hooksは同じコンポーネントのすべてのレンダーにおいて、安定した呼び出し順序に依存しています。これは実際にはうまく機能します。なぜなら、上記のルール(「Hooksはトップレベルでのみ呼び出す」)に従えば、Hooksは常に同じ順序で呼び出されるからです。さらに、linterプラグインがほとんどの間違いを検出します。
内部的には、Reactはすべてのコンポーネントに対して状態ペアの配列を保持しています。また、現在のペアのインデックスを保持しており、レンダリング前に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を使用するために理解する必要はありませんが、これは役立つメンタルモデルになるかもしれません。
状態は分離され、プライベートです
状態は、画面上のコンポーネントインスタンスに対してローカルです。言い換えれば、同じコンポーネントを2回レンダリングすると、各コピーは完全に分離された状態を持つことになります!一方を変更しても、他方には影響しません。
この例では、以前のGallery
コンポーネントが、そのロジックを変更せずに2回レンダリングされています。各ギャラリー内のボタンをクリックしてみてください。それらの状態が独立していることに注目してください。
import Gallery from './Gallery.js'; export default function Page() { return ( <div className="Page"> <Gallery /> <Gallery /> </div> ); }
これが、モジュールの先頭で宣言する可能性のある通常の変数と状態が異なる理由です。状態は特定の関数呼び出しやコード内の場所に結び付けられているのではなく、画面上の特定の場所に「ローカル」です。2つの<Gallery />
コンポーネントをレンダリングしたため、それらの状態は別々に保存されます。
また、Page
コンポーネントがGallery
の状態について何も「知らず」、状態を持っているかどうかさえ知らないことに注意してください。propsとは異なり、状態は、それを宣言するコンポーネントに対して完全にプライベートです。親コンポーネントはそれを変更できません。これにより、他のコンポーネントに影響を与えることなく、任意のコンポーネントに状態を追加または削除できます。
両方のギャラリーの状態を同期させたい場合はどうすればよいでしょうか?Reactでそれを行う正しい方法は、子コンポーネントから状態を削除し、最も近い共有親に追加することです。次のいくつかのページでは、単一のコンポーネントの状態を整理することに焦点を当てますが、このトピックについてはコンポーネント間で状態を共有するで戻ってきます。
まとめ
- コンポーネントがレンダリング間で何らかの情報を「記憶」する必要がある場合は、状態変数を使用します。
- 状態変数は、
useState
Hookを呼び出すことによって宣言されます。 - Hooksは
use
で始まる特別な関数です。それらは、状態のようなReactの機能に「フック」することを可能にします。 - Hooksはインポートを思い起こさせるかもしれません。それらは無条件に呼び出す必要があります。
useState
を含むHooksの呼び出しは、コンポーネントまたは別のHookのトップレベルでのみ有効です。 useState
Hookは、現在の状態とその更新関数という2つの値を返します。- 複数の状態変数を持つことができます。内部的には、Reactはそれらを順序で一致させます。
- 状態はコンポーネントに対してプライベートです。2つの場所にレンダリングすると、各コピーは独自の状態を取得します。
チャレンジ 1の 4: ギャラリーを完成させる
最後の彫刻で「次へ」を押すと、コードがクラッシュします。クラッシュを防ぐためにロジックを修正してください。イベントハンドラーにロジックを追加するか、アクションが不可能な場合はボタンを無効にすることでこれを行うことができます。
クラッシュを修正した後、前の彫刻を表示する「前へ」ボタンを追加します。最初の彫刻ではクラッシュしないはずです。
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} /> </> ); }