CS Fundamentals Trainer · Guides
React foundations for full-stack work: state, effects, forms, API calls and tests
The React a full-stack developer uses every day: components and props, state and immutable updates, derived values instead of copied state, when an effect is (and is not) the right tool, forms and validation, calling a backend API with loading, error and caching handled, routing, TypeScript props, accessibility and testing with Testing Library and MSW. The guide on advanced React covers re-renders, memoization and data-fetching internals.
8 min read
React builds a user interface from components: functions that take data and return a description of what should be on screen. React keeps the screen in sync with that description when the data changes. Everything in this guide follows from one rule: the UI is a function of state. You change state, React re-runs your components and updates the DOM for you.
Components and props
A component is a function that returns JSX. Props are its inputs, passed like attributes and read-only inside the component.
interface ListingCardProps {
title: string;
priceCents: number;
onSelect: (title: string) => void;
}
export function ListingCard({ title, priceCents, onSelect }: ListingCardProps) {
return (
<article className="listing-card">
<h3>{title}</h3>
<p>{(priceCents / 100).toFixed(2)} / week</p>
<button onClick={() => onSelect(title)}>Choose {title}</button>
</article>
);
}
- Keep components small and named after what they show. Compose them: a page renders sections, sections render cards.
- Data flows down through props; events flow up through callback props (
onSelect). childrenlets a component wrap arbitrary content (<Card>…</Card>), which avoids long lists of props.- Typing props with TypeScript catches most integration mistakes between components at build time.
State
State is data that a component remembers between renders and that changes over time: the text in an input, whether a menu is open, the items in a cart.
const [count, setCount] = useState(0);
Calling the setter schedules a new render with the new value. Three rules prevent most bugs:
- Treat state as immutable. Create new objects and arrays instead of changing them:
setItems([...items, item]),setUser({ ...user, name }),items.filter(...),items.map(...). React compares references; mutating in place means React may not notice the change. - State updates are not immediate. Inside the same event handler,
countstill has the old value aftersetCount(count + 1). When the new value depends on the old one, use the updater form:setCount((c) => c + 1). - Do not copy what you can compute. If
fullNamecomes fromfirstandlast, compute it during render. Copying props or other state into state creates two sources of truth that drift apart. Store the minimum and derive the rest.
Where state lives: in the closest common parent of the components that need it ("lifting state up"). Pass it down as props. When many distant components need the same value (the signed-in user, the theme), use Context or a small store such as Zustand. Server data is different: it belongs in a data-fetching cache (see below), not in hand-written global state.
Lists and keys
<ul>
{listings.map((l) => (
<li key={l.id}>{l.title}</li>
))}
</ul>
key tells React which item is which between renders. Use a stable id from your data. An array index as key breaks when items are inserted, removed or reordered: state and input values attach to the wrong rows.
Effects: synchronising with the outside world
useEffect runs code after React has updated the screen, to keep something outside React in sync with state: a subscription, a timer, a browser API, a third-party widget.
useEffect(() => {
const id = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(id); // cleanup: runs before the next effect and on unmount
}, []); // dependencies: when to re-run
- List every value from the component that the effect uses in the dependency array; the lint rule
react-hooks/exhaustive-depschecks it. Missing dependencies cause effects that read stale values. - Always clean up subscriptions and timers. In development, Strict Mode runs effects twice on mount to surface missing cleanups.
- You often do not need an effect. Computing a value from props or state belongs in render. Reacting to a user action belongs in the event handler (
onSubmit), not in an effect that watches state. Resetting state when a prop changes can be done with akey. Fetching data is better done with a data-fetching library than with a bare effect, which has to handle race conditions and caching by hand.
Forms
A controlled input takes its value from state and reports changes through onChange:
const [email, setEmail] = useState('');
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
That makes the value available for validation and conditional UI on every keystroke. For larger forms, a library such as React Hook Form keeps inputs mostly uncontrolled (the DOM holds the value) for performance and handles validation, often with a schema (Zod) shared with the types.
Good form behaviour:
- Every input has a visible
<label>connected to it (htmlForandid, or wrapping). - Validate on the client for fast feedback, and always validate again on the server: Django or DRF errors are the source of truth. Map field errors from the API (
{"email": ["Already in use"]}) back onto the fields. - Disable the submit button while a request is pending, so a double click does not send two requests, and show the error when it fails.
<form onSubmit>withevent.preventDefault()keeps Enter-to-submit working.
Talking to the backend
A component that needs server data has to handle loading, errors, empty results, stale data and out-of-order responses. A data-fetching library such as TanStack Query (React Query) or SWR handles those for you and gives you a cache keyed by the request:
function useListings(city: string) {
return useQuery({
queryKey: ['listings', city],
queryFn: () => api.get<Listing[]>(`/api/listings/?city=${encodeURIComponent(city)}`),
});
}
function ListingList({ city }: { city: string }) {
const { data, isPending, isError } = useListings(city);
if (isPending) return <p>Loading…</p>;
if (isError) return <p role="alert">Could not load listings.</p>;
if (data.length === 0) return <p>No rooms in {city} yet.</p>;
return <ul>{data.map((l) => <li key={l.id}>{l.title}</li>)}</ul>;
}
Writes are mutations; after one succeeds, invalidate the queries whose data changed (queryClient.invalidateQueries({ queryKey: ['listings'] })) so the screen shows fresh data.
Practical points with a Django backend:
- Keep the API calls in one small client module (base URL, JSON parsing, error handling) and call it from hooks, not from scattered components.
- With session authentication, send cookies (
credentials: 'include'across origins, the default on the same origin) and the CSRF token from thecsrftokencookie in theX-CSRFTokenheader onPOST,PUT,PATCHandDELETE. - Treat a
401as "signed out" in one place (for example, redirect to the login page), and show403and404as messages, not crashes. - In development, a Vite proxy (
server.proxyinvite.config.ts) forwards/apito Django, which avoids CORS while you work.
Routing
React Router (or the router of a framework such as Next.js or Remix) maps URLs to components. Put meaningful state in the URL: the current page, filters and the selected item, so links can be shared and the back button works. useParams reads path parameters and useSearchParams reads the query string.
Accessibility is part of correctness
- Use the right element:
<button>for actions,<a href>for navigation, headings in order, lists for lists. They come with keyboard support and roles for free. - Images need
alttext (emptyalt=""for decorative ones). Icon-only buttons need an accessible name (aria-label). - Errors that appear after an action should be announced (
role="alert"or a live region). - Test with the keyboard only, and run an automated checker such as axe.
Testing
React Testing Library tests components the way a user uses them: find elements by role and label, interact, and check what is on screen. MSW (Mock Service Worker) intercepts network requests so tests use realistic API responses without a real server.
it('shows the listings for a city', async () => {
server.use(http.get('/api/listings/', () => HttpResponse.json([{ id: 1, title: 'Sunny room' }])));
render(<ListingList city="Recife" />, { wrapper: QueryProvider });
expect(await screen.findByText('Sunny room')).toBeInTheDocument();
});
- Query by role and name (
getByRole('button', { name: 'Save' })) before falling back to test ids; that also checks accessibility. - Use
findBy…(async) for things that appear after a request. - Use
userEventrather than firing raw events. - Unit tests for components and hooks, plus a few end-to-end tests (Playwright or Cypress) that drive the real frontend against the real backend for the critical paths (sign in, book, pay).
Project setup
Vite with the React and TypeScript template is the usual starting point for a single-page app talking to a separate API. Add ESLint with the React hooks rules and Prettier from the first day. Environment-specific values (the API URL) come from import.meta.env and must not include secrets: everything in the frontend bundle is public.
Common mistakes
- Mutating state (
items.push(x); setItems(items)): React may not re-render. - Copying props into state, then wondering why the component does not update.
- Fetching in
useEffectwithout handling cancellation, so a slow old response overwrites a newer one. - Effects with missing dependencies, which read stale values.
- Index keys on lists that change.
- Validation only on the client.
- A
divwithonClickinstead of abutton.
Sources
- react.dev: Learn React, especially "Managing State", "You Might Not Need an Effect" and "Synchronizing with Effects".
- TanStack Query documentation.
- Testing Library: guiding principles and queries and MSW documentation.
- MDN: Accessibility.
Practise this topic: React