Skip to content
Theone Coleman.Shared openly.

// Practical lesson / React

Make a button remember its state.

Build a React toggle with useState, a stable accessible button name and clear saved-state feedback. Test it by mouse, keyboard and refresh.

What you’ll make possible

Build and check an accessible saved/not-saved toggle, while understanding where the state is kept.

A button can remember a saved/not-saved choice while its component is mounted. React state keeps that value between renders. Refreshing the page resets this example; it does not create a lasting reading list.

useState gives you the current value and a setter that requests the next value. Here, false means not saved and true means saved. Keep the Hook at the top level of the component.

import { useState } from 'react';

export default function SaveButton() {
  const [saved, setSaved] = useState(false);

  return (
    <>
      <button
        type="button"
        aria-pressed={saved}
        onClick={() => setSaved(current => !current)}
      >
        Save for later
      </button>
      <p role="status">
        {saved ? 'Saved for this session.' : 'Not saved.'}
      </p>
    </>
  );
}

The updater receives the pending value and returns its opposite. React then renders with the new value. Pass the click handler as a function; calling it during rendering would request an update immediately.

This is a toggle button. Its accessible name stays “Save for later” in both states, while aria-pressed exposes its current state. A separate status line makes the result visible. This follows the WAI button pattern for a toggle with aria-pressed.

type="button" makes the intention explicit. If you later place this example inside a form, it changes the saved state rather than submitting the form.

If nothing changes, check that SaveButton is rendered, useState is imported and onClick receives a function. Do not call setSaved directly in the component body or move the Hook inside a condition.

A reset after refresh is the intended result. A lasting reading list needs a separate storage design: decide where records should live, who needs access and what should happen on another device.

Try two independent SaveButton components. Each keeps its own state. Use the related React resource and official documentation to take the example further.

// Your turn

Try this.

  1. Render SaveButton in a disposable React project. Confirm “Not saved” is shown and aria-pressed is false.

  2. Click the button. Confirm “Saved for this session” appears and aria-pressed becomes true.

  3. Click again. Confirm “Not saved” returns and aria-pressed becomes false.

  4. Use Tab to reach the button. Test Space and Enter, checking each state change.

  5. Inspect the accessibility tree. The name remains “Save for later” while the pressed state changes.

  6. Refresh the page. The example starts unsaved again.

References & credits3 sources

Sources checked . Features and terms can change.