React State, Effects and Data Fetching
useState, controlled forms, lifting state up, useEffect done right, and fetching data with loading and error states.
State Is Data That Changes the Screen
The previous lesson rendered a fixed study plan. Real users need to mark a session complete, add a revision task, or load a saved plan. State is component-owned data that can change over time. When you update state using its setter, React renders again using the new value. A local variable does not do that: changing a normal variable is invisible to React.
Use state for values that change in response to user actions or external data. For a study planner, that might be the task list, the text being typed into a form, or a request status. Avoid creating state for values that can be calculated from existing state, such as the number of completed tasks.
| Value | State? | Reason |
|---|---|---|
| Current task array | Yes | Users can add or complete tasks |
| New-task input text | Yes | It changes on each keystroke |
| Number of completed tasks | Usually no | Calculate it from the task array |
| A static page heading | No | It does not change during interaction |
Update State Without Mutating It
useState returns the current value and a setter. For a value derived from its previous value, use the functional setter form. Arrays and objects should be replaced with new values rather than edited in place, so React receives a new reference and the update is easy to reason about.
import { useState } from "react"
type Task = { id: string; title: string; completed: boolean }
export function TaskBoard() {
const [tasks, setTasks] = useState<Task[]>([
{ id: "sql-1", title: "Practise joins", completed: false },
{ id: "math-1", title: "Review probability", completed: false },
])
function toggleTask(taskId: string) {
setTasks((current) => current.map((task) =>
task.id === taskId ? { ...task, completed: !task.completed } : task
))
}
return (
<ul>
{tasks.map((task) => (
<li key={task.id}>
<label>
<input type="checkbox" checked={task.completed}
onChange={() => toggleTask(task.id)} />
{task.title}
</label>
</li>
))}
</ul>
)
}Updating one task creates a new array and a new object for that task. Other task objects are reused because their contents did not change. The checkbox is controlled: its checked value comes from state, and the change handler requests a state update.
Use Controlled Inputs for Planner Data
A controlled input gets its value from React state and reports edits through an event handler. That keeps validation and displayed values aligned. A form should also work with the keyboard: use a real form, a labelled input, and handle its submit event rather than making a clickable text element.
import { FormEvent, useState } from "react"
type TaskDraft = { title: string; subject: string }
export function AddTaskForm({ onAdd }: { onAdd: (draft: TaskDraft) => void }) {
const [title, setTitle] = useState("")
const [subject, setSubject] = useState("")
const canSubmit = title.trim().length > 0 && subject.trim().length > 0
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
if (!canSubmit) return
onAdd({ title: title.trim(), subject: subject.trim() })
setTitle("")
setSubject("")
}
return (
<form onSubmit={submit}>
<label>Session title <input value={title}
onChange={(event) => setTitle(event.target.value)} /></label>
<label>Subject <input value={subject}
onChange={(event) => setSubject(event.target.value)} /></label>
<button type="submit" disabled={!canSubmit}>Add session</button>
</form>
)
}In a larger form, display validation feedback next to the relevant field and explain how to fix it. Client-side checks improve the experience but are not a security boundary: the server must validate the submitted data too.
Put Shared State at the Nearest Common Parent
If the task list, progress card, and form all need the same tasks, move that state to the closest component that contains all three. Pass values down as props and pass event callbacks down for requested changes. This is called lifting state up. It avoids keeping separate copies of the same plan in each child.
import { useState } from "react"
type Task = { id: string; title: string; completed: boolean }
export function PlannerPage() {
const [tasks, setTasks] = useState<Task[]>([])
const completed = tasks.filter((task) => task.completed).length
function addTask(title: string) {
setTasks((current) => [...current, {
id: crypto.randomUUID(), title, completed: false,
}])
}
return (
<main>
<ProgressCard planned={tasks.length} completed={completed} />
<AddTaskForm onAdd={(draft) => addTask(draft.title)} />
<TaskList tasks={tasks} />
</main>
)
}Here completed is derived during render, not stored separately. In production, choose an ID strategy that is supported in the environment where the code runs, and do not assume a browser-only API exists in server code.
Use Effects to Synchronise with External Systems
An effect runs after React has committed a render and is for synchronising with something outside React: a network request, browser event listener, timer, or third-party widget. It is not a general place to put every calculation. If a value can be derived from props and state during render, calculate it there instead.
The dependency list describes the reactive values the effect reads. Omitting a dependency can leave the effect using stale values; adding an unstable object created during render can make it repeat too often. Effects that subscribe or start work should clean up when dependencies change or the component unmounts.
import { useEffect, useState } from "react"
type Plan = { id: string; title: string }[]
type Result = { plan: Plan | null; loading: boolean; error: string | null }
export function useStudyPlan(studentId: string): Result {
const [result, setResult] = useState<Result>({
plan: null, loading: true, error: null,
})
useEffect(() => {
const controller = new AbortController()
setResult({ plan: null, loading: true, error: null })
fetch("/api/study-plans/" + encodeURIComponent(studentId), {
signal: controller.signal,
})
.then(async (response) => {
if (!response.ok) throw new Error("Could not load the plan")
return response.json() as Promise<Plan>
})
.then((plan) => setResult({ plan, loading: false, error: null }))
.catch((error: unknown) => {
if (error instanceof Error && error.name === "AbortError") return
setResult({ plan: null, loading: false, error: "Please try again." })
})
return () => controller.abort()
}, [studentId])
return result
}This simple pattern includes loading, success, and error states and cancels an obsolete request if the learner changes. Framework data-fetching tools often handle caching and race conditions more completely; the next lesson shows the server-first approach in Next.js.
Make Loading, Empty, Error and Success Visible
A blank panel during a request is ambiguous. Explicitly model what the user sees while the plan loads, when it has no sessions, when a request fails, and when data is available. Avoid flashing old results under a new student's name: clear or label data when the request key changes.
- Start a request when its input key changes.
- Show a pending message or skeleton, with an accessible status announcement.
- Check response.ok because fetch resolves even for many HTTP error statuses.
- Parse and validate the response before trusting the data shape.
- Show a concise recovery action on failure and preserve details in safe server logs.
For a real planner, request cancellation is only one part of correctness. Also consider stale responses, cache policy, authentication, and what happens if a student submits twice. Keep network error messages useful without exposing internal stack traces.
Common Mistakes
Mutating a state array with push
Why: The reference does not change and existing renders may be reused.
Fix: Create a replacement with map, filter, or spread syntax.
Putting derived counts in separate state
Why: The count can fall out of sync when the source list changes.
Fix: Calculate the count from the task list during rendering.
Using an effect to copy props into state
Why: It creates two sources of truth and an extra render.
Fix: Render from the prop directly unless the user is editing a deliberate local draft.
Ignoring loading, failure, or cleanup
Why: Users see ambiguous screens and outdated responses can overwrite newer ones.
Fix: Model request states and abort or otherwise guard obsolete work.
Turn the Plan into a Useful Interaction
Practice
A stateful weekly planner
- Add a controlled form for a title, subject, and planned minutes with clear field labels.
- Lift the task array to the page and let the form request additions through a callback.
- Add a completion checkbox and derive the completed-session count from the array.
- Load a plan from an endpoint and display loading, empty, error, and success states.
- Change the selected student while a request is pending and verify an older result cannot replace the newer plan.
Hint: Use immutable updates and check response.ok. Keep server-side validation in the API even after adding client-side feedback.
🎯 Key Takeaways
- ✓State holds values that change the UI; update it with setters to request a render.
- ✓Replace arrays and objects rather than mutating them.
- ✓Controlled forms keep input state, validation, and UI in sync.
- ✓Lift shared state to the nearest common parent and pass callbacks downward.
- ✓Use effects for external synchronization, with complete dependencies and cleanup.
- ✓Represent loading, empty, error, and success states explicitly.
- Use React's official documentation for state, effects, and forms. Next.js server rendering can simplify data loading for many page requests.
Next
What comes next
Style components with Tailwind CSS, build responsive layouts, use an accessible component library, and keep styles consistent.
Lesson 03 · Styling React Apps — Tailwind and Component Libraries →HELP US IMPROVE
How was this lesson?
Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.
Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.
