学习库ReactStructuring State

Structuring State

Choose minimal state, avoid contradictions, and preserve or reset it intentionally.

更新于 适用于 React 19.2

State shape determines how many impossible combinations an interface can enter. Keep one source of truth and calculate derived values during rendering.

Remove redundant state

Courses.tsx
const [courses, setCourses] = useState(initialCourses);
const [filter, setFilter] = useState("all");
const visibleCourses = courses.filter((course) => filter === "all" || course.status === filter);

Storing visibleCourses separately would require synchronizing two values. Prefer IDs over duplicate selected objects when the source collection already holds the record.

Preserve and reset by identity

React preserves state while the same component remains at the same tree position. A key can intentionally reset it.

Editor.tsx
<LessonEditor key={lesson.slug} lesson={lesson} />

Keep this

Store the minimum truth, avoid contradictory flags, normalize shared records, and use component identity to control reset behavior.

学习位置已保存在此设备上。