TechDojoPilot Cohort Week 2 · Day 9

Pilot CohortPhase 1Week 2Day 9

React State, Forms and Lists

Your day, about 6 hours

  1. Learn2 hSections 4 to 9
  2. Build2 hSection 10, then the P1 scope draft
  3. Flex1 hJournals, then catch-up, section 11
  4. Stand-up1 hLive, 9 pm WAT
01

Daily theme and context

Day 8's components show data, but nothing on screen can change yet. Today adds state: data that changes while the app is running, such as who has been marked present, what someone has typed into a form, or which filter is selected. When state changes, React redraws the parts of the screen that depend on it. This is the moment the Tracker starts to behave like a real application.

Today is also the first proper test of judging AI-written code (skill 3 in your self-rating): the AI writes a component, and you review it against a checklist before it goes anywhere near your app. And in the last 30 minutes of the Build block, you draft the scope of your P1.

This is Week 2 of the Pilot Cohort's six-week Learn phase ("Frontend"), Day 9 of 30 learning days. Day 9 starts at the Thursday (26 Nov) 9 pm class; its work goes into Quest 2, due by Sunday 29 Nov, 11:59 pm WAT. It has four blocks, about 6 hours, done whenever suits you except the stand-up: Learn (2 hours, covered in full below), Build (2 hours, section 10: the Learner Project Tracker and the P1 scope draft), Flex (1 hour: your three journals first, then catch-up, then the optional open-source practice in section 11), and the live stand-up at 9 pm WAT (1 hour).

02

Learning objectives

By the end of today, the learner should be able to:

  1. Explain what state is, and when something should be state rather than a normal variable or a value calculated from other data.
  2. Use useState to store and update state, and update arrays and objects without changing them in place.
  3. Build a controlled form in React with validation messages.
  4. Render conditionally (show or hide parts of the screen) and render lists with stable keys.
  5. Share state between components by keeping it in one parent and passing data and functions down as props, and decide what belongs in a component and what belongs in a page.
  6. Review AI-written React code against a checklist and record every problem found.
03

Prerequisite knowledge

Day 8's Next.js app with the layout, the Learner type, and the LearnerCard and StatusBadge components; Day 7's form validation and four states. Your Day 7 discovery conversation: if you moved it, hold it before the last 30 minutes of today's Build block, because the P1 scope draft is built on it.

04

TechDojo core lesson

35 minutes

State: data that changes

Props come from outside a component. State belongs to the component and can change over time. In React you create it with useState:

"use client";
import { useState } from "react";

export default function PresentCounter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Present: {count}</button>;
}

useState(0) gives two things: the current value (count) and a function to change it (setCount). Calling setCount tells React the data changed, and React redraws the component. Changing count directly (count = count + 1) does nothing visible, because React never hears about it.

In Next.js, any component that uses state or responds to clicks needs "use client"; as its very first line. Friday explains why.

State can hold any type. For a list of learners, give useState the type in angle brackets: useState<Learner[]>(sampleLearners) means "an array of Learner objects, starting with the sample data". Add present: boolean to your Learner type (and present: false to each sample learner), so attendance has somewhere to live.

PropsCome from outside
  • Passed in by the parent
  • Read-only for the component
StateBelongs to the component
  • Created with useState
  • Changed only through its setter
  • Changing it redraws the screen

Never change state in place

When state is an array or object, don't modify it; make a new one:

// Wrong: changes the same array, so React may not notice
learners.push(newLearner);
setLearners(learners);

// Right: a new array with the old items plus the new one
setLearners([...learners, newLearner]);

// Marking one learner present: a new array, with a new object for the changed one
setLearners(learners.map((l) => (l.id === id ? { ...l, present: true } : l)));

The ... (spread) copies the old items or properties into the new array or object. This is why Day 6 stressed that map and filter return new arrays: they are the tools for updating state safely.

Sharing state: keep it in one place, pass it down

The attendance list, the dashboard counts and the registration form all need the same list of learners. So the list lives in one parent component, and the children get what they need as props, including functions to change it:

// components/TrackerBoard.tsx
"use client";
import { useState } from "react";
import { learners as sampleLearners, Learner } from "@/lib/learners";
import AttendanceList from "@/components/AttendanceList";

export default function TrackerBoard() {
  const [learners, setLearners] = useState<Learner[]>(sampleLearners);

  function markPresent(id: number) {
    setLearners(learners.map((l) => (l.id === id ? { ...l, present: true } : l)));
  }

  return <AttendanceList learners={learners} onMarkPresent={markPresent} />;
}
// components/AttendanceList.tsx
type AttendanceListProps = { learners: Learner[]; onMarkPresent: (id: number) => void };

as sampleLearners renames the import in this file, so it doesn't clash with the state's name. (id: number) => void is the type of a function that takes a number and returns nothing. The child calls onMarkPresent(l.id); the parent changes the state; React redraws everything that uses it. Only TrackerBoard needs "use client": components it imports run in the browser with it. app/page.tsx just shows <TrackerBoard /> and stays as it is.

  1. 1TrackerBoardHolds the learner list in state
  2. 2Props downlearners and onMarkPresent go to the children
  3. 3Child calls the functiononMarkPresent(l.id) on a click
  4. 4Parent updates stateA new array; React redraws everything that uses it

What should be state, and what shouldn't

Keep in state only what can't be worked out from something else. The list of learners is state. The number absent is not: calculate it from the list each time (learners.filter((l) => !l.present).length). If you stored it separately, the two would eventually disagree, and that is one of the most common React bugs.

A filter works the same way. The chosen filter is state (const [filter, setFilter] = useState("all")); the learners it shows are calculated from it each time, for example const shown = filter === "at-risk" ? learners.filter((l) => attendanceRate(l) < 70) : learners;.

StateCan't be worked out from anything else
  • The learner list
  • What's typed in a field
  • The chosen filter
Calculate itWorked out from state each time
  • Number absent
  • Number at risk
  • The filtered list

Controlled forms

In React, a form input's value is held in state, and every keystroke updates it:

const [name, setName] = useState("");
<input value={name} onChange={(e) => setName(e.target.value)} />

This is called a controlled input: React is always the single source of truth for what's in the field. On submit, check the values (as on Day 7), keep the messages in state too, and only then add the new item:

const [nameError, setNameError] = useState("");

<form noValidate onSubmit={(e) => {
  e.preventDefault();
  if (name.trim() === "") {
    setNameError("Enter the learner's full name.");
    return;
  }
  setNameError("");
  onAdd(name.trim());   // a function passed down from TrackerBoard
  setName("");
}}>
  <label htmlFor="name">Full name</label>
  <input id="name" value={name} onChange={(e) => setName(e.target.value)} aria-describedby="name-error" />
  <p id="name-error">{nameError}</p>
  <button type="submit">Register</button>
</form>

Two JSX spellings differ from HTML: for becomes htmlFor, and novalidate becomes noValidate. return stops the function early, so nothing is added while a message is showing.

Conditional rendering

Show something only when a condition is true:

{absentCount > 0 && <p>{absentCount} learner(s) still absent</p>}
{learners.length === 0 ? <p>No learners yet.</p> : <LearnerList learners={learners} />}

Watch the first pattern: if the left side is the number 0, React shows "0" on the page. Write a real true-or-false test (absentCount > 0), not just absentCount &&.

Event handlers: pass the function, don't call it

onClick={markPresent} passes the function for React to call later. onClick={markPresent(id)} calls it immediately, during drawing, which usually causes errors. When you need to pass a value, wrap it: onClick={() => markPresent(id)}.

Components versus pages

A useful rule: a page decides what data to show; components decide how to show it. The attendance page holds the learners in state and passes them down; LearnerCard just displays one learner. If a piece of UI appears in more than one place, or is getting long, make it a component.

05

Video resource

15 minutes
Web Dev Simplified, "Learn useState In 15 Minutes - React Hooks Explained" Open on YouTube

Watch it in full.

Guided viewing questions:

  1. What two things does useState give you, and what is each for?
  2. Why does the video recommend the "function" form of the setter, setCount((c) => c + 1), in some cases?
  3. What goes wrong if you store an object in state and then change one of its properties directly?
06

Reading resource

15 minutes
React, "State: A Component's Memory"react.dev React, "Rendering Lists"react.dev React, "Conditional Rendering"react.dev

Skim both; you met the ideas in the core lesson.

Guided reading questions:

  1. Why doesn't a normal variable inside a component keep its value between renders?
  2. According to "Rendering Lists", where should a list item's key come from, and what should it never be?
  3. Rewrite {count && <p>…</p>} so it can never show a stray "0".
07

Interactive exercise

40 minutes
  1. 15 min By hand: an attendance list where each learner has a "Mark present" button, plus a line showing how many are still absent, calculated from the list (not stored in its own state).
  2. 20 min Judging AI code: in a new OpenCode session, ask it to reply with the code rather than create files, so you review it before it touches your app: "Write a React component in TypeScript for Next.js that shows a list of learners and lets an instructor mark each one present or absent." Before using any of it, review it against this checklist and write down every problem you find:
    • Are the props and data typed, and do the types match your Learner type?
    • Does every list item have a stable key (an id, not the array position)?
    • Is state updated with new arrays and objects, never changed in place?
    • Is anything stored in state that could be calculated instead?
    • Do click handlers pass functions rather than call them?
    • Do inputs and buttons have clear labels for screen readers?
    • Does it actually meet your acceptance criteria from Day 2 (for example, "a learner cannot edit their own attendance")?
  3. 5 min Fix the problems you found, or reject the component and keep your own, and note which and why.
08

AI-assisted learning prompt

After your own review, compare notes with an AI. Your free chat assistant is fine for this, and it saves your OpenCode allowance for code:

Prompt

Here is a React component and the review checklist I used: [paste both]. Here are the problems I found: [list them]. Don't fix the code. Tell me whether any of my findings are wrong, and whether I missed any problem the checklist covers.

Log both reviews in the AI-use journal: what you found, what the AI added, and any finding of yours it disagreed with (and who was right, once you checked).

09

Knowledge check

15 minutes
  1. What happens on screen if you change a state value directly instead of calling its setter? Why?
  2. Write the code that adds newLearner to a learners state array without changing the original array.
  3. Should "number of learners at risk" be its own state? Explain your answer.
  4. What is the difference between onClick={save}, onClick={save()} and onClick={() => save(id)}?
  5. What is a controlled input, and why does React prefer it for forms?
  6. The attendance list and the dashboard both need the learner list. Where should the state live, and how does the attendance list change it?
  7. TrackerBoard starts with "use client". Why don't AttendanceList or app/page.tsx need it?
10

Build block: Learner Project Tracker, then the P1 scope draft

2 hours

Tracker (about 90 minutes), using sample data in state (it won't be saved permanently until Week 3). Keep the learner list in one TrackerBoard client component, as in the core lesson, and build each section as its own component that gets props from it:

  • Dashboard (home page): number of learners, number at risk, and today's attendance count, all calculated from state.
  • Learner directory: the full list using LearnerCard, with a filter (all, on track, at risk).
  • Attendance: mark each learner present or absent; the count updates immediately.
  • Registration: Day 7's form, rebuilt as a controlled React form with the same validation messages, adding learners to state.

For now these can live on one page as separate sections. Tomorrow you'll give each its own route. If time runs short, do attendance and registration first; the dashboard and the filter can follow over the weekend, since Quest 2 is due on Sunday. Work on a branch and merge through a pull request.

P1 scope draft (last 30 minutes). Using your Day 6 problem list and Day 7 discovery notes, draft the first three parts of the P1 scope document (tomorrow you finish all eight). They're Week 1's tools, used on your own problem:

  1. Problem statement and evidence (Day 1): who has it, what happens today, what it costs them, one direct quote, and your answers to the four problem questions with evidence from the conversation.
  2. Assumption register (Day 1): at least five things you believe but haven't confirmed, each with a confidence level and how you'd check it.
  3. Users and the main workflow (Day 2): who will use it, and the one main thing they do with it, step by step.
11

Flex hour: open-source practice

Optional

Do your three journals first (about 20 minutes). Then catch up on the Build work: today's is the biggest build of the week. Only if you're on track, use the rest for the optional open-source practice.

12

Deliverables and submission criteria

Nothing is submitted today. Today, start section D (State, routes and going live) of your Tracker Frontend Pack and draft your P1 scope. You hand both in for Quest 2 by Sunday 29 Nov, 11:59 pm WAT. Today's work should contain:

0 of 7 ticked Ticks are saved on this device only.

13

Daily journal reflection

Add today's entry to your three running journals (they're section E of your Frontend Pack):

  • Engineering journal: One bug that came from state (something didn't update, or updated twice) and how you found it. Estimate vs actual: for today's Tracker milestone, record your estimate, the actual time, and the reason for any big gap.
  • AI-use journal: The full review of the AI-written component: problems found, the AI's second opinion, what you kept.
  • Curriculum journal: Did the checklist make reviewing AI code easier? Was 30 minutes enough to start the P1 scope?