Skip to content
Sarj Code Standards

prefer-coordinated-react-state

Review repeated setter groups adopting fields from one incoming record.

Why

Separately writable fields repeatedly adopted and reset together duplicate the bookkeeping of one record. Future transitions can omit a slot. This is a structural review opportunity, not evidence of an existing inconsistency, a race, or multiple rendered frames.

Fix

Review one typed record for the observed slots. Keep independent state separate, preserve every initializer and functional updater, and review all readers, request identities, cancellation, retained data and property evaluation before changing ownership. The rule offers no automatic fix.

Examples

Before — flagged Direct adoption and reset repeat one page's bookkeeping
src/page.tsx
import { useState } from "react";
type Page = { rows: string[]; cursor: string | null };
export function View() {
const [rows, setRows] = useState<string[]>([]);
const [cursor, setCursor] = useState<string | null>(null);
function adopt(page: Page) {
setRows(page.rows);
setCursor(page.cursor);
}
function reset() {
setRows([]);
setCursor(null);
}
return (
<button onClick={reset} onDoubleClick={() => adopt({ rows: [], cursor: null })}>
{rows.length}
{cursor}
</button>
);
}
After — preferred One record preserves the page fields
src/page.tsx
import { useState } from "react";
type Page = { rows: string[]; cursor: string | null };
export function View() {
const [page, setPage] = useState<Page>({ rows: [], cursor: null });
function adopt(next: Page) {
setPage(next);
}
function reset() {
setPage({ rows: [], cursor: null });
}
return (
<button onClick={reset} onDoubleClick={() => adopt({ rows: [], cursor: null })}>
{page.rows.length}
</button>
);
}

References