Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

React docs
React
Getting Started with ReactProject StructureCore ConceptsData and StateTestingBuild and Deployment
Discussions

React guide · 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.

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.
Questions about this chapter?
Previous chapterCore ConceptsNext chapterTesting

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.