1
1

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のuseStateについて解説したいと思います。

Last updated at Posted at 2025-02-10

React:useStateについて

使用する目的

React において、クライアントサイドでデータを更新するためには、再レンダリングが必要です。通常の変数管理では再レンダリングを起こすことができません。そこで useState を使用することで、指定した変数に変化があった場合に再レンダリングが発生し、画面が更新されます。

使い方

次に、useState の使い方について説明します。以下の例では、age という変数を管理します。

page.tsx

import React, { useState } from 'react';

const ExampleComponent = () => {
  const [age, setAge] = useState(0);
  
  const increaseAge = () => {
    setAge(age + 1);
  };

  return (
    <div>
      <p>Age: {age}</p>
      <button onClick={increaseAge}>Increase Age</button>
    </div>
  );
};

export default ExampleComponent;

【POINT】

  • useState の返り値は2つあり、最初の値 (age) は初期値を示し、2つ目の値 (setAge) は状態を更新するための関数です
  • useState(0) は初期値を0に設定します
  • 状態を更新するためには、setAge 関数を使用します。例えば、setAge(age + 1) で age を1つ増やすことができます

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

useState を使用することで再レンダリングが発生するタイミングは以下の通りです。

  • 初回読み込み時
  • set 関数が実行されたタイミング
  • 親コンポーネントで再レンダリングが発生した場合

Next.js での注意点

Next.js では、デフォルトでサーバーサイドレンダリングが行われます。しかし、useState を使用する場合はクライアントサイドでのレンダリングが必要です。これを指定するために、コンポーネントの冒頭に use client を宣言する必要があります

page.tsx
'use client';

import React, { useState } from 'react';

(先ほどのコードと同じ)

補足:SSG,SSR,CSRについて

これらの用語は、レスポンスのデータをどこで、いつレンダリングするのかを示すものです。

  • SSG (Static Site Generation):

・どこで: ビルド時にサーバーでレンダリング
・いつ: ビルド時に一度だけレンダリングされ、その後は静的ファイルとして配信
・特徴: 高速なページ読み込み、SEOに強い。

  • SSR (Server-Side Rendering):

・どこで: リクエスト時にサーバーでレンダリング
・いつ: ユーザーのリクエストごとにレンダリング
・特徴: 動的なコンテンツが必要な場合に有効、SEOに強いがレスポンス時間が長くなる場合がある

  • CSR (Client-Side Rendering):

・どこで: クライアント(ブラウザ)でレンダリング
・いつ: JavaScriptがブラウザで実行されたときにレンダリング
・特徴: 初回ロードが遅くなるが、その後のページ間移動が速い、SEOに弱い

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?