本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開TASTEWINMファイル管理開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペース投資TASTESTOCK株式自動売買デスクトップアプリはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらくTASTEWINM2つの画面で整理する、キーボード中心のファイルマネージャー

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

投資

TASTESTOCKいつ・何を。自分で決めたルールどおりに動く株式自動売買

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシー会社概要プライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
昨日
累計閲覧
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

React ドキュメント
React
Getting Started with ReactProject StructureCore ConceptsData and StateTestingBuild and Deployment
ディスカッション

React ガイド · 4/6

Data and State

この章は現在、英語でのみ提供しています。

This chapter covers lifting state up, context, reducers, data fetching and forms.

Lifting state up

When two components need the same data, move the state to their closest common parent and pass the value and a setter down as props, so the data has a single source of truth.

import { useState } from "react";

function TemperatureInput({ value, onChange }: { value: number; onChange: (v: number) => void }) {
  return <input type="number" value={value} onChange={(e) => onChange(Number(e.target.value))} />;
}

export function Thermostat() {
  const [celsius, setCelsius] = useState(20);
  return (
    <div>
      <TemperatureInput value={celsius} onChange={setCelsius} />
      <p>{(celsius * 9) / 5 + 32} °F</p>
    </div>
  );
}

Passing data deeply with context

Passing values like the theme through many levels of props (prop drilling) gets tedious. Create a context with createContext, provide a value near the top, and any component below can read it with useContext. Current React renders the context itself as the provider; older code uses <ThemeContext.Provider>.

import { createContext, useContext } from "react";

type Theme = "light" | "dark";
const ThemeContext = createContext<Theme>("light");

export function App({ theme }: { theme: Theme }) {
  return (
    <ThemeContext value={theme}>
      <Toolbar />
    </ThemeContext>
  );
}

function Toolbar() {
  const theme = useContext(ThemeContext);
  return <div className={`toolbar toolbar-${theme}`}>Theme: {theme}</div>;
}

Components reading a context re-render when its value changes, so split contexts by purpose.

Centralizing updates with useReducer

useReducer gathers many kinds of updates into one function: components dispatch actions describing what happened, and the reducer computes the next state. A discriminated union type for actions catches unhandled cases.

import { useReducer } from "react";

type Todo = { id: number; text: string; done: boolean };
type Action =
  | { type: "added"; text: string }
  | { type: "toggled"; id: number };

function todosReducer(todos: Todo[], action: Action): Todo[] {
  switch (action.type) {
    case "added":
      return [...todos, { id: Date.now(), text: action.text, done: false }];
    case "toggled":
      return todos.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
  }
}

export function useTodos() {
  const [todos, dispatch] = useReducer(todosReducer, []);
  return { todos, add: (text: string) => dispatch({ type: "added", text }), dispatch };
}

A reducer plus context covers global state in small apps; larger apps may benefit from Zustand or Redux Toolkit.

Fetching server data

You can call fetch inside an effect, but abort the request in the cleanup function to avoid race conditions between responses.

この章について質問がありますか?
前の章Core Concepts次の章Testing
import { useEffect, useState } from "react";

type User = { id: number; name: string };

export function UserName({ userId }: { userId: number }) {
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    const controller = new AbortController();
    fetch(`/api/users/${userId}`, { signal: controller.signal })
      .then((res) => res.json() as Promise<User>)
      .then(setUser)
      .catch((err) => {
        if (err.name !== "AbortError") console.error(err); // ignore aborts
      });
    return () => controller.abort();
  }, [userId]);

  return <span>{user ? user.name : "Loading…"}</span>;
}

Caching, retries, loading and error states and background refetching are hard to get right by hand, so real apps often use TanStack Query. Wrap the app in QueryClientProvider in main.tsx, then:

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

type Todo = { id: number; title: string };

export function Todos() {
  const queryClient = useQueryClient();
  const { data, isPending, error } = useQuery({
    queryKey: ["todos"],
    queryFn: async (): Promise<Todo[]> => (await fetch("/api/todos")).json(),
  });
  const addTodo = useMutation({
    mutationFn: (title: string) =>
      fetch("/api/todos", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ title }),
      }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["todos"] }),
  });

  if (isPending) return <p>Loading…</p>;
  if (error) return <p>Error: {error.message}</p>;
  return (
    <>
      <ul>{data.map((t) => <li key={t.id}>{t.title}</li>)}</ul>
      <button onClick={() => addTodo.mutate("New task")}>Add</button>
    </>
  );
}

Handling forms

Controlled components bind an input's value to state, which helps when validating on every keystroke. Current React also accepts a function in <form action={...}>, with useActionState reporting the result and pending state.

import { useActionState } from "react";

type State = { error: string | null };

async function subscribe(_prev: State, formData: FormData): Promise<State> {
  const email = String(formData.get("email") ?? "");
  if (!email.includes("@")) return { error: "Please enter a valid email." };
  await fetch("/api/subscribe", { method: "POST", body: formData });
  return { error: null };
}

export function SubscribeForm() {
  const [state, formAction, isPending] = useActionState(subscribe, { error: null });
  return (
    <form action={formAction}>
      <input name="email" type="email" required />
      <button disabled={isPending}>{isPending ? "Sending…" : "Subscribe"}</button>
      {state.error && <p role="alert">{state.error}</p>}
    </form>
  );
}

For large forms with complex validation, React Hook Form is a good companion.

Summary

  • Lift shared state up to the closest common parent.
  • Use context for deeply shared values and useReducer for complex updates.
  • Abort effect-based fetches in cleanup, or use TanStack Query.
  • Handle forms with controlled inputs or form actions plus useActionState.

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。