Skip to content
engineering workbench.by StudyPort Academy
Learning path
Intermediate22 minLESSON 03 / 8

Events and state

01

Understand the idea

A form field on a React page should show whatever your JavaScript state currently holds. When the user types, you update that state, and React draws the field again.

State is memory between renders

In the JavaScript track you stored values in variables. In a React , a normal variable resets every time the function runs. is how React remembers a value from one to the next.

useState is a - a function whose name starts with use. You call it with a starting value, for example the string Ada. It gives you back two things: the current value (name) and a setter function (setName).

When you call setName with a new string, React runs the component again with that new name.

Events update state

onChange runs when the user changes a field. onClick runs when they click. onSubmit runs when they submit a form.

For a form submit, call event.preventDefault() so the browser does not reload the page and wipe your state.

Then update state from the event. For text-like fields, use event.target.value. For a checkbox, use event.target.checked (a boolean), not value.

Controlled fields, one pattern

A means: the React state is the source of truth.

  • The input’s value (or checked) comes from state.
  • onChange writes the new value into state.
  • React re-renders, and the input shows the new state.

If you set the input value from name but never call setName, the field looks frozen. If you skip value and only use a plain HTML input, React is not driving that field.

Common form controls
ControlWhat you storeWhat you read in onChange
text inputa stringevent.target.value
textareaa stringevent.target.value
selecta stringevent.target.value
checkboxtrue or falseevent.target.checked
radio groupone string for the whole groupevent.target.value

In the live example, name, notes, team, and onCall each follow that pattern. The day and night radios show the shape of a radio group; the logged record focuses on the four state values above.

Several fields, one form

You can use several useState calls (as the example does) or one state object. On submit, those values together are the record you would send to a server.

Disable Save when required fields are empty. Reset by setting state back to the starting values - the inputs will follow because they are controlled.

How to read the live example

  1. Four useState lines set the starting record.
  2. Five console.log lines print that record (onCall is printed with String so the console shows true or false clearly).
  3. Each field’s value/checked comes from state; each onChange calls the matching setter.
  4. preventDefault on submit keeps you on the page.

Change the name in the preview. The component renders again, and the first console line should show what you typed.

02

Mental model

FOLLOW THE VALUE

state
value prop
input

The screen shows state.

01 / 03Trace the transformation

03

Live example

The example keeps name, notes, team, and onCall in state. The console prints those values. Change a field in the preview and watch the console update on the next render.

import { useState } from "react"; // State for controlled fields.
export default function App() {
  const [name, setName] = useState("Ada"); // Text input state.
  const [notes, setNotes] = useState("notes"); // Textarea state.
  const [team, setTeam] = useState("team"); // Select state.
  const [onCall, setOnCall] = useState(true); // Checkbox boolean.
  console.log(name); // Current name from state.
  console.log(notes); // Current notes from state.
  console.log(team); // Current team from state.
  console.log(String(onCall)); // Checkbox as a string for the console.
  console.log("submitted"); // Marker that the form values are ready.
  return (
    <form onSubmit={(event) => event.preventDefault()}> {/* Stay on the page. */}
      <input aria-label="Name" value={name} onChange={(event) => setName(event.target.value)} /> {/* Controlled text. */}
      <textarea aria-label="Notes" value={notes} onChange={(event) => setNotes(event.target.value)} /> {/* Controlled textarea. */}
      <select aria-label="Team" value={team} onChange={(event) => setTeam(event.target.value)}> {/* Controlled select. */}
        <option value="team">team</option>
        <option value="solo">solo</option>
      </select>
      <label>
        <input type="checkbox" checked={onCall} onChange={(event) => setOnCall(event.target.checked)} /> {/* Use checked, not value. */}
        On call
      </label>
      <label>
        <input type="radio" name="shift" value="day" checked readOnly /> {/* Day option in the group. */} Day
      </label>
      <label>
        <input type="radio" name="shift" value="night" checked={false} readOnly /> {/* Night option in the group. */} Night
      </label>
      <button type="submit">Save</button>
    </form>
  );
}

VISUAL FLOW

Try the same flow interactively

State holds the value. The input shows that value. Typing updates state, then React draws the input again.

Step 1 of 5

Click through a controlled input

name

Ada

setName

ready

Remember the starting value

const [name, setName] = useState("Ada");

name is the current string. setName is how you change it. A plain variable would reset every render.

04

Guided challenge

Log the checkbox as a boolean

The on-call field logs on. Change it so the log is the boolean true, which is what a controlled checkbox stores.

import { useState } from "react";
export default function App() {
  const [onCall, setOnCall] = useState(true); // The real checkbox value is a boolean.
  console.log("Ada"); // Keep the name log.
  console.log("notes"); // Keep the notes log.
  console.log("team"); // Keep the team log.
  console.log("on"); // Wrong - log String(onCall) instead.
  console.log("submitted"); // Keep the submitted log.
  return (
    <form onSubmit={(event) => event.preventDefault()}> {/* Stay on the page. */}
      <label>
        <input type="checkbox" checked={onCall} onChange={(event) => setOnCall(event.target.checked)} /> {/* Boolean from checked. */}
        On call
      </label>
      <button type="submit">Save</button>
    </form>
  );
}

EXPECTED CONSOLE OUTPUT

Ada
notes
team
true
submitted

Hints 0/2

    05

    Free sandbox

    Make a variation, test an assumption, or break the example on purpose. This draft is saved separately.

    import { useState } from "react";
    export default function App() {
      const [name, setName] = useState("Ada"); // One controlled field to edit freely.
      return (
        <form onSubmit={(event) => event.preventDefault()}> {/* Stay on the page. */}
          <input value={name} onChange={(event) => setName(event.target.value)} /> {/* State drives the value. */}
          <p>{name}</p> {/* The screen shows the same state. */}
          <button type="submit">Save</button>
        </form>
      );
    }
    
    
    06

    Quiz

    A quick check for understanding. Retry as often as you like; your learning path stays open.

    01What makes an input controlled?
    02Which event property is the checkbox’s boolean?

    Ready to call this one understood?

    Mark this lesson complete to earn 150 XP. You can always revisit it.

    Sign in to save progress
    Next lesson