What it is
State is the data that determines what the interface currently shows. An event such as a click changes that data, and rendering updates the screen. A component packages related behavior and presentation; it does not make every value global.
Why you need it
If the DOM, a variable, and a stored value all disagree, bugs become difficult to explain. A clear source of truth makes transitions and derived values predictable.
How it works
- Represent the current state explicitly.
- Handle an event that changes the state.
- Derive display values from that state.
- Render the result and clean up external subscriptions when their owner goes away.
A complete small state transition
<button id="increment">Add one</button>
<p id="count" aria-live="polite"></p>
<script>
let count = 0;
const output = document.querySelector("#count");
function render() { output.textContent = `Count: ${count}`; }
document.querySelector("#increment").addEventListener("click", () => {
count += 1;
render();
});
render();
</script>The count is the source of truth; text is derived from it. Frameworks automate parts of rendering, but the state/event relationship remains. This standalone page’s listener lives for the lifetime of the page.
Good practices and why
- Keep state close to its owner and derive values instead of maintaining redundant copies.
- Use stable record identity for editable lists and remove subscriptions when components are destroyed.
Common mistakes
- Using list position as identity when records can move.
- Assuming asynchronous syntax moves CPU-heavy work off the main thread.
Try it yourself
Add a reset button and a rule that disables increment at five. Derive the disabled condition from count rather than a second independent flag.
What a successful result looks like
Reset restores both the display and enabled state, and the count never exceeds the defined limit.
0 / 6000 characters · Saved on this device. Do not include passwords or private data.
Check your understanding
Answer the understanding check correctly to record exercise completion.
Related interview practice
- The timer says zero. It still runs last. ↗
- After sorting, the input belongs to the wrong row. ↗
- Each navigation adds another click handler. ↗
These scenarios add constraints and follow-up questions to the concepts you just learned.
Further reading
Selected primary references · reviewed 2026-10-09. Examples are educational; use your framework’s documented integration guidance when building a deployed system.