Keep browser UI state consistent
Quick answer
Separate application data from its visual representation. An event handler updates a small state object, then a render function derives text, checked state and disabled state from that data. Keep transient values local where appropriate. Update only the necessary nodes so focus and editing state are not destroyed by needless replacement.
Browser examples
Run each snippet in a fresh browser document. These are static code blocks; ByteMind browser execution is not verified. Storage examples require a test origin.
const state={qty:0},out=document.createElement("output"),b=document.createElement("button");function render(){out.textContent=String(state.qty);b.disabled=state.qty===0;}render();console.log(out.textContent,b.disabled);state.qty=2;render();console.log(out.textContent,b.disabled);Expected console output:
0 true2 falseBoth displayed quantity and button state follow one data value.
const b=document.createElement("button");let n=0;b.addEventListener("click",()=>n++);b.disabled=true;b.click();b.disabled=false;b.click();console.log(n);Expected console output:
1The disabled button does not activate through click().
Common mistake
Avoid reading a button label as the authoritative business state. Avoid replacing a focused input merely to update a separate count.
Practice
Create a quantity counter with a lower bound of zero; keep the display and decrement button state derived from one value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Keep browser UI state consistent — Knowledge Check
Apply the concept and predict the browser example behavior.
Which value should be authoritative in a small counter application?
Why update only the necessary DOM nodes?
How should a decrement button behave at quantity zero?
What is the exact console output in Keep browser UI state consistent example 1?
const state={qty:0},out=document.createElement("output"),b=document.createElement("button");function render(){out.textContent=String(state.qty);b.disabled=state.qty===0;}render();console.log(out.textContent,b.disabled);state.qty=2;render();console.log(out.textContent,b.disabled);What is the exact console output in Keep browser UI state consistent example 2?
const b=document.createElement("button");let n=0;b.addEventListener("click",()=>n++);b.disabled=true;b.click();b.disabled=false;b.click();console.log(n);