Comparing 3 Paradigms of State and Form Management in React
If you wrote React back when Redux reigned supreme, you are likely all too familiar with the dread of handling forms. Even a simple user profile update could devour hundreds of lines of code. Today, the React community generally falls into 3 main approaches:
- Approach 1: Client State Containers (Redux Toolkit, Zustand). Components manage every input via
useState. You must handleonSubmit, prevent page reloads withe.preventDefault(), triggerfetch(), and dispatch actions to update the store. For a 10-field form, you burn at least 50 lines of code just to synchronize state and catch validation errors. - Approach 2: Server State Libraries (TanStack Query / SWR + React Hook Form). This is a massive step forward, separating server cache from client state. Still, the code overhead remains substantial. You must write custom
useMutationhooks, manually remember to invalidate query keys (queryClient.invalidateQueries), and cram in cumbersomeonMutateandonErrorlogic if you want Optimistic Updates. - Approach 3: Web Standards + Route Modules (Remix / React Router v7). A return to web fundamentals: leveraging native HTML
<form>tags, HTTP GET forloaderfunctions, and HTTP POST/PUT/DELETE foractionfunctions. Each route file handles both backend and frontend. Once an action finishes executing, the framework automatically revalidates all on-screen data without requiring manual refetch calls.
Weighing the Options: Which Solution Fits Your Project?
There is no silver bullet for every problem. Here is a practical breakdown based on projects I have worked on:
1. Redux Toolkit / Zustand
- Pros: Granular control over every piece of client state, backed by an exceptional DevTools ecosystem. Ideal for apps with intricate client-side state, such as Figma-like canvases or audio players.
- Cons: Excessive boilerplate. You must manually manage
isLoading,isError, and form resets. Worst of all is the risk of data drift between the client store and the database when multiple tabs are open.
2. TanStack Query (React Query)
- Pros: Outstanding caching, request deduplication, and background refetching. Cuts boilerplate by roughly 60% compared to vanilla Redux.
- Cons: Decouples client and backend APIs. You still have to maintain a separate API layer, which risks network waterfalls when nested child components trigger independent
useQuerycalls.
3. React Router v7 / Remix (Loader/Action + Nested Routes)
- Pros: Completely eliminates the need for state managers to handle server data. Nested Routes load 100% of parent and child route data in parallel from the initial request, eradicating waterfalls. Optimistic UI is built-in via the
useFetcherhook with under 10 lines of code. - Cons: Requires a solid grasp of web fundamentals (HTTP verbs, FormData, Request/Response APIs) rather than the familiar habit of “firing events to update state.”
Why Is React Router v7 Ideal for CRUD Applications?
Let’s face reality: over 80% of state in order management systems, CMS platforms, or social networks is simply a temporary client-side mirror of the database.
Using Redux to manage this kind of data is like using a sledgehammer to crack a nut. React Router v7 (inheriting its architecture from Remix) tackles this problem head-on. You declare data fetching (loader) and form mutation (action) functions right inside the same route file. On submit, the form sends requests straight to that action. Once the server finishes running the action, the framework automatically re-triggers all relevant loaders to refresh the UI. No useEffect. No redundant state variables.
Hands-on: Building a Task Board with Nested Routes and Optimistic UI
Let’s dive into building a complete task board from database to user interface.
Step 1: Initialize the Project
Open your terminal and run the following commands:
npx create-react-router@latest my-task-app
cd my-task-app
npm install prisma @prisma/client
npx prisma init --datasource-provider sqlite
Open prisma/schema.prisma and add a simple Task model:
model Task {
id String @id @default(uuid())
title String
status String @default("PENDING")
createdAt DateTime @default(now())
}
Push the schema to your local SQLite database:
npx prisma db push
Step 2: Write Loaders and Actions for the Route
Create app/routes/tasks.tsx. This file serves simultaneously as a backend endpoint and a UI component:
import { Form, useLoaderData, useNavigation, Outlet } from "react-router";
import type { Route } from "./+types/tasks";
import { prisma } from "~/db.server";
// 1. LOADER: Runs 100% on the server upon GET requests
export async function loader() {
const tasks = await prisma.task.findMany({
orderBy: { createdAt: "desc" },
});
return { tasks };
}
// 2. ACTION: Runs 100% on the server upon receiving POST from <Form>
export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData();
const title = formData.get("title");
if (typeof title !== "string" || !title.trim()) {
return { error: "Title cannot be empty" };
}
await prisma.task.create({
data: { title: title.trim(), status: "PENDING" },
});
return { success: true };
}
// 3. UI COMPONENT
export default function TasksLayout() {
const { tasks } = useLoaderData<typeof loader>();
const navigation = useNavigation();
// Check if the create form is submitting
const isSubmitting = navigation.formData?.get("title") != null;
return (
<div style={{ display: "flex", gap: "2rem", padding: "2rem" }}>
<div style={{ flex: 1 }}>
<h2>Task List</h2>
{/* Standard form: No onChange or useState needed */}
<Form method="post" style={{ marginBottom: "1.5rem" }}>
<input
type="text"
name="title"
placeholder="Enter new task name..."
required
disabled={isSubmitting}
/>
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Saving..." : "Add task"}
</button>
</Form>
<ul>
{/* Optimistic item: Displayed immediately when the user clicks submit */}
{isSubmitting && (
<li style={{ opacity: 0.5, fontStyle: "italic" }}>
{String(navigation.formData?.get("title"))} (Creating...)
</li>
)}
{tasks.map((task) => (
<li key={task.id}>
<span>{task.title} - [{task.status}]</span>
</li>
))}
</ul>
</div>
{/* Mount point for child routes */}
<div style={{ flex: 1, borderLeft: "1px solid #ccc", paddingLeft: "1rem" }}>
<Outlet />
</div>
</div>
);
}
Step 3: Optimize Task Interactions with useFetcher
Using useNavigation works great for creation forms or page transitions. However, if each task row has a “Complete” button, using the default <Form> tag causes the browser to update the URL and potentially trigger unwanted scrolling. This is where useFetcher shines.
Each fetcher has an independent lifecycle, allowing you to send payloads to actions in the background without altering the URL:
import { useFetcher } from "react-router";
export function TaskItem({ task }: { task: { id: string; title: string; status: string } }) {
const fetcher = useFetcher();
// Check the outgoing request
const isToggling = fetcher.formData?.get("intent") === "toggle-status";
// Optimistic State: Read value from submitting form data, fallback to initial task.status
const nextStatus = fetcher.formData?.get("nextStatus");
const currentStatus = isToggling && typeof nextStatus === "string"
? nextStatus
: task.status;
return (
<li style={{ display: "flex", alignItems: "center", gap: "8px" }}>
<span style={{ textDecoration: currentStatus === "COMPLETED" ? "line-through" : "none" }}>
{task.title}
</span>
<fetcher.Form method="post" action={`/tasks/${task.id}/toggle`}>
<input type="hidden" name="intent" value="toggle-status" />
<input
type="hidden"
name="nextStatus"
value={currentStatus === "COMPLETED" ? "PENDING" : "COMPLETED"}
/>
<button type="submit">
{currentStatus === "COMPLETED" ? "Reopen" : "Complete"}
</button>
</fetcher.Form>
</li>
);
}
The moment the user clicks, the text strikes through instantly with zero latency. Once the server finishes processing, the loader revalidates the data automatically and accurately. If the server returns a 500 error, the fetcher seamlessly rolls back the UI to its initial state without requiring a single client-side try/catch block.
Tips for Debugging FormData and JSON Responses
Working with actions requires reading and debugging FormData fairly often. When dealing with complex nested payloads or inspecting action responses, you can use online JSON formatting tools such as toolcraft.app/en/tools/developer/json-formatter to format payloads quickly without manually logging the entire object to the console.
Step 4: Seamless Experience Even Without JavaScript (Progressive Enhancement)
The greatest strength of this architecture lies in its resilience. Suppose a user enters an elevator with a flaky connection; even if JavaScript hasn’t finished loading, the <Form method="post"> tag still submits data seamlessly using standard browser form behavior.
The browser sends an HTTP POST request to the server. The server executes the action, saves changes to the database, and returns the updated HTML. The app keeps working seamlessly without a single extra line of fallback code.
