ProgramGuru

useState: Component Memory

useState: Component Memory

A classroom counter must remember how many students have arrived. A local variable initialized in the component starts again on the next render and does not ask React to update the screen when assigned.

useState adds memory to a component instance. It returns the current value and a setter function. Calling the setter requests a new render with the next stored value; React preserves that memory while the component keeps its identity.

  1. Explain

    Read the value and setter returned by useState.

  2. Trace

    Request an arrival update and predict the next visible count.

  3. Apply

    Calculate remaining places from the count rather than duplicating state.

useState: follow the relationship

  1. Stored count: 0

    The current render displays no arrivals.

  2. Request count: 1

    The click handler asks the setter to update the stored count.

  3. Next screen: 1

    React renders the next count and its derived remaining places.

Read this relationship alongside the complete code. This diagram explains the flow; it does not execute React.

Build the mental model

State is for information that can change and must influence the interface. A fixed heading is not state. A value calculated from current state, such as remaining places, can usually be calculated during render rather than stored separately.

Separate memory from derived information

Duplicating remaining places in state creates two values to update for one arrival. If one setter is forgotten, the counter and remaining number disagree. Computing remaining from capacity and present avoids this contradiction and clarifies which quantity is independently changeable.

The initial argument is used for the initial state rather than resetting the state on every render. An expensive initial calculation can be supplied through a lazy initializer function. Keep that initializer pure, because development checks may evaluate it again to detect accidental side effects.

Read the complete React example

The example initializes present to zero and requests an increment on a click. The practice also calculates remaining from capacity minus present. Those two displayed values therefore always agree because only present is independently stored.

React · JavaScript with JSX

import React, { useState } from 'react';
export default function App() {
  const [present, setPresent] = useState(0);
  return <main><p>Present: {present}</p><button onClick={() => setPresent(previous => previous + 1)}>Student arrived</button></main>;
}

Expected screen and behavior

Initial screen: Present: 0 Student arrived
After selecting Student arrived: the screen includes Present: 1.

Connect the source to the screen

React · main example

import React, { useState } from 'react';
export default function App() {
  const [present, setPresent] = useState(0);
  return <main><p>Present: {present}</p><button onClick={() => setPresent(previous => previous + 1)}>Student arrived</button></main>;
}

The setter schedules an update; it does not assign to the current render’s variable. React calls the component again with the new value, and the JSX from that render describes the changed counter. Functional updates are useful when the next value depends on the previous value.

Avoid the common mistakes

Call useState at the component’s top level, never inside a condition or loop. State belongs to each component instance, not to the function definition globally. Removing a component can discard its state; persistent storage requires a separate design.

Practice before reading the solution

React · starting example

import React, { useState } from 'react';
export default function App() {
  const [present, setPresent] = useState(0);
  return <main><p>Present: {present}</p><button onClick={() => setPresent(previous => previous + 1)}>Student arrived</button></main>;
}

Count arrivals until a three-place study group is full.

Predict the initial visible text and explain which values determine it. Then inspect the worked solution below. Change one relevant input in your local project and check whether the screen follows your prediction. A working screen should be checked for the intended meaning, not merely the absence of an error.

Worked practice solution

The practice disables the arrival button once the group reaches capacity. Remaining is derived from the one stored count. Disabling the control prevents another ordinary click but does not replace server-side capacity enforcement in a real booking system.

React · JavaScript with JSX

import React, { useState } from 'react';
export default function App() {
  const [present, setPresent] = useState(0);
  const capacity = 3;
  const remaining = capacity - present;
  return <main><p>Present: {present}</p><p>Remaining places: {remaining}</p><button disabled={remaining === 0} onClick={() => setPresent(previous => previous + 1)}>Add student</button></main>;
}

Expected screen and behavior

Initial screen: Present: 0 Remaining places: 3 Add student
After selecting Add student: the screen includes Remaining places: 2.
After selecting Add student: the screen includes Remaining places: 1.

Check your reasoning

Choose the explanation that matches React and JavaScript behavior. Review the reasoning for each alternative before moving on.

Why does an ordinary local counter fail to provide React memory?
Choose one answer. You can try again.

Answer and explanation

It is recreated during rendering and assignment does not request a render

Correct. useState provides retained memory plus an update request mechanism.

Use the idea in the next lesson

useState adds memory to a component instance. It returns the current value and a setter function. Calling the setter requests a new render with the next stored value; React preserves that memory while the component keeps its identity.

Continue with State as a Snapshot. Revisit Handling Events when the relationship between inputs and the resulting screen needs another look.

Read the primary reference: React documentation on useState: Component Memory.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: State as a Snapshot →