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>
  );
}

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:

  1. 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.
  2. State updates are not immediate. Inside the same event handler, count still has the old value after setCount(count + 1). When the new value depends on the old one, use the updater form: setCount((c) => c + 1).
  3. Do not copy what you can compute. If fullName comes from first and last, 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

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:

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:

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

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();
});

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

  1. Mutating state (items.push(x); setItems(items)): React may not re-render.
  2. Copying props into state, then wondering why the component does not update.
  3. Fetching in useEffect without handling cancellation, so a slow old response overwrites a newer one.
  4. Effects with missing dependencies, which read stale values.
  5. Index keys on lists that change.
  6. Validation only on the client.
  7. A div with onClick instead of a button.

Sources

Practise this topic: React

More guides