Intermediate35 minJavaScriptState

State and UI Thinking

Build the mental model that connects data, user actions, and interface updates.

Learning Objectives

By the end of this lesson, you'll be able to:

  • βœ“ Explain Explain state as the information an interface needs to remember
  • βœ“ Describe Describe how events change state and trigger updates
  • βœ“ Identify Identify values that should be derived instead of stored separately
  • βœ“ Plan a small render loop before writing feature code

Why This Matters:

When you understand the state -> event -> update loop, later lessons about rendering, validation, and debugging feel much more manageable.

Before You Start:

You should be familiar with:

State as a Source of Truth

State is the information a feature needs to remember after the user does something. A dropdown remembers whether it is open. A filter remembers the selected category. A booking form remembers what the visitor typed.

The important shift is this: the browser page is the display layer, not the main memory. The DOM should reflect what your JavaScript knows. It should not be the only place where the truth lives.

  1. Read state

    Start from the values the feature remembers, such as the selected category.

  2. Make a decision

    Work out what should change, such as which cards to show and which button to highlight.

  3. Update the UI

    Render the visible result so the page matches the latest state.

Good interface code starts with remembered values, then decides what the page should show.

Events and Updates

An event is not the whole feature. It is the moment something happens: a click, a form submission, a checkbox toggle, or an input change. The event handler should update state clearly, then let the interface update from that new state.

Useful discipline: ask two questions for every feature: What values changed? What parts of the page now need to match those values?

Derived UI Decisions

Not every interface detail deserves its own stored variable. Some values are better derived from other state: item counts, empty-state messages, button labels, or whether a result list should appear at all.

  • Store the selected filter.
  • Derive the filtered item count.
  • Store the search term.
  • Derive whether the empty-state message should show.

Running Example: Quiz Game State

Here is what state looks like in the Quiz Game project before the UI gets more complicated. See the full Quiz Game project

script.js

Why this structure helps: The feature remembers only the values it truly needs: where the learner is, what they picked, what the score is, and what phase the interface is in.

⏸️ Checkpoint for Understanding

Before moving forward, can you answer these?

  1. Why is it useful to treat state as the source of truth instead of reading values back from the page each time?
  2. What is a derived value in an interface?
  3. Predict what happens if two different event handlers update the same feature without agreeing on one state object.

Tips to Remember:

  • If the page and the data can disagree, your state model is probably too blurry.
  • Derived values help the interface stay consistent without duplicating logic.
Check Your Answers
  1. Because the page is the display layer. Keeping the important values in JavaScript makes it easier to reason about updates, compare old and new values, and avoid contradictory UI states.
  2. It is something the UI calculates from existing state, such as whether a button should be disabled, how many items match a filter, or what label to show after a user action.
  3. The feature becomes harder to trust because the UI can drift out of sync. One part of the code may think the feature is open while another part thinks it is closed.

How confident are you with this concept?

πŸ˜• Still confused | πŸ€” Getting there | 😊 Got it! | πŸŽ‰ Could explain it to a friend!

Guided Practice: Plan a Filterable Feature

Use plain English first so the JavaScript structure stays understandable.

Step 1: Name the state before writing DOM code

Imagine a filterable menu with category buttons and a result count. Write down the smallest set of values the feature needs to remember. For example: selectedCategory, items, and searchTerm.

Keep this list short. If a value can be calculated later, it probably does not need to be stored separately.

πŸ’‘ Need a hint?
Store the selected category, not the highlighted button colour.
Store the search term, not the rendered HTML.

Step 2: Map one event to one update

Pick one user action, such as clicking a category button. Describe what changes in state when that action happens, and what part of the page should update afterward.

Use a short sentence like: When the user clicks Dessert, update selectedCategory, then render the filtered list and count.

πŸ’‘ Need a hint?
Separate the event itself from the UI update that follows it.
If the action changes nothing in state, it probably should not change the display either.

Step 3: Identify two derived UI details

List two things the interface can derive from state rather than store directly. Example: the count of matching cards, or whether the empty-state message should be visible.

πŸ’‘ Need a hint?
Derived values are often booleans, counts, or labels.
If the value can be recomputed at any time, derive it.

Step 4: Sketch the render loop

Write a tiny flow in plain English: read current state, calculate what should appear, then update the relevant DOM areas. The goal is a stable sequence, not fancy code.

πŸ’‘ Need a hint?
Good UI code has a repeatable order.
Read state first, then decide, then render.

You're on track if you can:

  • ☐ You identified the minimum state values the feature needs
  • ☐ You linked a user event to a specific state change
  • ☐ You separated stored state from derived UI details
  • ☐ You described a repeatable render/update sequence

πŸ’ͺ Independent Practice

Choose a familiar builder-path interface and write its state story before coding it.

Your Task:

Pick a small interactive feature such as a menu filter, FAQ accordion, gallery category switcher, or booking form. Write a short planning note that answers four things: what state the feature stores, what events can change it, what values are derived, and what parts of the interface must update after each action.

Requirements:
  • Name at least three stored or derived values
  • Describe at least two user actions
  • Explain which interface regions update after each action
Stretch Goals (Optional):
  • Note one contradictory UI state you want to avoid
  • Sketch a tiny render function in pseudocode

Success Criteria:

CriteriaYou've succeeded if...
Clear state modelThe learner stores only the values the feature genuinely needs to remember.
Event clarityEach user action updates state in a predictable, explainable way.
Derived thinkingCounts, labels, or visibility rules are calculated from state instead of duplicated.
UI consistencyThe page would not show conflicting signals after repeated user actions.

Recap

  • State is what the feature remembers.
  • Events change that remembered information.
  • The UI should be updated from state, not improvised one DOM change at a time.
  • Counts, labels, and visibility rules are often best derived from existing values.

Lesson Complete: What You Learned

Key Takeaways:

  • State is the information your feature needs to remember between user actions.
  • The page should display state, not replace it as the source of truth.
  • Events change state, and rendering decisions follow from those changes.
  • Derived values help you avoid storing the same idea in multiple places.

Learning Objectives Review:

Look back at what you set out to learn. Can you now:

  • βœ… Explain state, events, and rendering as one connected interface loop Check!
  • βœ… Choose what should be stored versus what should be derived Got it!
  • βœ… Describe how one user action should change one feature state Can explain it!
  • βœ… Plan a clearer UI update sequence before writing DOM code Could teach this!

If you can confidently answer "yes" to most of these, you're ready to move on!

Think & Reflect:

Source of Truth

  • Which feature you have built recently would become clearer with a simple state object?
  • What values were you previously trying to remember through the DOM alone?

πŸ€” Real-World Test:

Menus, carts, search panels, booking widgets, and navigation drawers all rely on the same mental pattern: remember the important values, respond to actions, then update the interface from those values.

🎯 Looking Ahead:

Next, you will use this model to render repeated content from arrays and objects without duplicating markup.

Recommended Next Steps

Practice Projects

Apply what you've learned with these hands-on projects:

Color Switcher

A compact feature for practising state-driven visual updates.

JavaScriptUI
Start Project

Photo Gallery 2

A richer builder-path project where category and rendering decisions matter.

JavaScriptGallery
Start Project

Progress tracking is disabled. Enable it in to track your completed tutorials.