Machine Coding · Lesson 2 of 12 · 3 min
Interactive UI Basics: Counter & Toggle
This isn't about building a counter. It's about demonstrating you have a clear mental model for UI: state, events, and rendering. Get this wrong, and you fail the round.
The Core UI Loop: State, Events, Render
All interactive UIs, from a simple toggle to a complex dashboard, follow the same pattern. A user action creates an event, the event handler updates a state variable, and a render function updates the DOM to reflect the new state.
Your job is to make this loop explicit. The state—a number for a counter, a boolean for a toggle—is the single source of truth. The DOM is just a reflection of that truth. Never the other way around.
This is the fundamental model that frameworks like React and Vue formalize. Showing you understand it from first principles is a huge green flag.
A Counter Implementation That Works
Let's build a counter that increments, decrements, and resets, with limits. Notice how one function, render(), is responsible for all DOM updates. It's called once at the start and then after every single state change.
This centralization is key. It guarantees the UI is always a correct representation of the state.
Here is the required HTML. Assume it's in the body.
<div class="counter-container">
<button id="decrement-btn">Decrement</button>
<span id="count-display">0</span>
<button id="increment-btn">Increment</button>
<button id="reset-btn">Reset</button>
</div>
And the script that powers it.
// 1. Define state and constants
let count: number = 0;
const MIN_COUNT: number = 0;
const MAX_COUNT: number = 10;
// 2. Get references to DOM elements
const decrementBtn = document.getElementById('decrement-btn') as HTMLButtonElement;
const incrementBtn = document.getElementById('increment-btn') as HTMLButtonElement;
const resetBtn = document.getElementById('reset-btn') as HTMLButtonElement;
const countDisplay = document.getElementById('count-display') as HTMLSpanElement;
// 3. The single function to sync DOM with state
function render(): void {
countDisplay.textContent = count.toString();
decrementBtn.disabled = count <= MIN_COUNT;
incrementBtn.disabled = count >= MAX_COUNT;
}
// 4. Event handlers only update state, then call render
function handleIncrement(): void {
if (count < MAX_COUNT) {
count++;
render();
}
}
function handleDecrement(): void {
if (count > MIN_COUNT) {
count--;
render();
}
}
function handleReset(): void {
count = MIN_COUNT;
render();
}
// 5. Attach listeners and perform initial render
incrementBtn.addEventListener('click', handleIncrement);
decrementBtn.addEventListener('click', handleDecrement);
resetBtn.addEventListener('click', handleReset);
render(); // Initial render to set correct button states
The Trap: Reading State from the DOM
The trap: A junior developer, when asked to increment the counter, will write code that reads the current value from the screen.
// DO NOT DO THIS
function handleIncrement() {
let currentValue = parseInt(countDisplay.textContent, 10);
currentValue++;
countDisplay.textContent = currentValue;
}
This is the single biggest mistake you can make. It signals you lack a mental model for UI development. Reading from the DOM is slow, error-prone (what if textContent is not a number?), and breaks the "state as the source of truth" principle. It makes debugging impossible as the application grows. Your state lives in a JavaScript variable. Period.
In an interview, if you even suggest reading from the DOM to get the current state, you've likely failed. The interviewer is testing whether you understand that UI is a function of state:
UI = f(state). Reading from the DOM inverts this relationship.
A toggle component has the same trap. Don't check if an element classList.contains('active') to decide what the next state should be. Use a boolean variable let isActive = false; as the source of truth.
How to Explain This in an Interview
When you get a problem like this, narrate your thought process using the state-driven model. It shows you're not just coding, you're architecting.
- "First, I'll define the state needed for this component. For a counter, it's a single number, initialized to 0. I'll also define constants for the min and max values."
- "Next, I'll identify the user actions that change this state. Here, we have clicks on the increment, decrement, and reset buttons."
- "Then, I'll write a single
renderfunction. Its only job is to update the DOM—the text display and the disabled status of the buttons—based on the current value of the state variable. This keeps our concerns separate." - "Finally, I'll attach event listeners. The handlers for these events will only modify the state variable, and then call the
renderfunction to update the UI. I'll also callrenderonce on initialization to ensure the UI is correct from the start."
This narration demonstrates a deliberate, scalable approach. You're not just hacking a solution together; you're implementing a pattern.
Try it
Implement a password visibility toggle. You'll need an <input type="password"> and a button.
- The state is a boolean, e.g.,
isPasswordVisible. - Clicking the button flips the boolean.
- The
renderfunction should change the input'stypeattribute betweenpasswordandtext, and maybe change the button's text from "Show" to "Hide". This should take you 15 minutes.
Next: We'll apply these principles to a non-interactive component in Building a Static Component: Star Rating.
Lock it in — apply this lesson under interview conditions.