Skills practised: Application state, Rendering from state.
04Explanation
A render function takes the current state and makes the page match it. It does not decide what changed; it simply redraws its part.
The pattern is: an event happens, an update function changes state, then render() runs.
list.replaceChildren(...nodes) swaps all the old children for new ones in one step, so items are never duplicated.
Build elements with createElement and textContent. Never put user text into innerHTML, because it can contain HTML or scripts.
Redrawing a small list from scratch is fast and simple. For large lists, keyed updates (reuse elements by id) preserve focus and scroll position; frameworks do this with a virtual DOM or fine-grained signals.
Keep render free of side effects other than the DOM: no fetches, no state changes. Then calling it twice gives the same page, which makes bugs easy to reproduce.
Re-rendering destroys and recreates elements, so listeners attached to them are lost. Delegate events to a container that render does not replace (Lesson 59).
If you do use templates with innerHTML, escape every interpolated value (&, <, >, ", '). Forgetting one is a cross-site scripting (XSS) hole.
05Definitions
Render
To update the page so it shows the current state.
Re-render
To run the render function again after the state changes.
replaceChildren
A DOM method that removes an element's children and inserts the given nodes.
XSS (cross-site scripting)
An attack where untrusted text is inserted as HTML and runs as code in the page.
Escaping
Converting special characters such as < and & so text is shown, not interpreted as HTML.
State-to-interface rendering explorer. Edit a state object and see the render function rebuild the interface, with the old and new markup side by side.
Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.
Rows appear twice
Replace children instead of appending.
const state = { names: ["Ada", "Lin"] };
const list = document.querySelector("#list");
function render() {
for (const name of state.names) {
const li = document.createElement("li");
li.textContent = name;
list.append(li);
}
}
render();
state.names.push("Sam");
render();
console.log(list.children.length);
Render a cart
Render rows and a derived total.
const state = { lines: [{ name: "Lamp", price: 30, qty: 2 }, { name: "Bulb", price: 5, qty: 3 }] };
function render() {
// TODO: one <tr> per line with two <td>: name and line total (price * qty)
// and #total text "Total: $75"
}
render();
console.log(document.querySelector("#rows").children.length, document.querySelector("#total").textContent);
A small rendered app
Connect events, updates and render.
// state = { value: 0 }. One delegated listener on #app calls
// update(action) then render(). render sets #value to the value and
// #note to "Negative!" when value < 0, otherwise "".
// Click: inc, inc, dec, dec, dec, then log value and note.
09Prediction
Commit to an answer first, then run the real code to compare.
// HTML: <ul id="l"><li>old</li></ul>
const l = document.getElementById("l");
l.replaceChildren(...["a", "b"].map((t) => Object.assign(document.createElement("li"), { textContent: t })));
console.log(l.children.length, l.textContent);
What is printed?
10Debugging investigation
A product name breaks the page
A product called "<b>Bold</b> lamp" shows as a bold word, and a name containing an img tag adds an image to the page.
const state = { products: ["Desk", "<b>Bold</b> lamp", "<img src=x alt=x>"] };
const list = document.getElementById("products");
function render() {
list.innerHTML = state.products.map((p) => "<li>" + p + "</li>").join("");
}
render();
console.log(list.querySelectorAll("b, img").length + " elements from names");
React, Vue and Svelte all follow the same idea: you describe the interface as a function of state, and the framework re-renders when state changes. Writing a few render functions by hand shows exactly what they automate.
function render() {
for (const t of state.items) list.append(make(t));
}
render appends without removing old items
map runs twice
createElement copies
The list is read-only
3. Why avoid innerHTML with user text?
It is slower
The text can be interpreted as HTML and run scripts (XSS)
It cannot show text
It removes listeners only
4. render() is called three times with the same state of 2 items, using replaceChildren. How many li are there?
6
2
3
0
5. What happens to listeners attached directly to elements that render replaces?
They move to the new elements
They are lost with the old elements
They double
They become global
6. Which keeps the page correct more easily?
Patch individual elements in each event handler
Update state, then call one render function
Store the HTML string in state
Reload the page after each change
13Solutions and tests
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
Rows appear twice: Prints 3; Rendering again keeps 3
Render a cart: Prints 2 Total: $75; Line totals; No innerHTML
A small rendered app: Prints -1 Negative!; Reset clears the note
The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-14-state-and-persistence/lesson-067-rendering-interfaces-from-state/. Every example on this page is generated from those files.
These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.
15Summary and next steps
Render functions build the interface from state.
Event → update state → render.
replaceChildren avoids duplicates.
Use textContent for user data, or escape every value.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationrendering from state
Context: I am learning rendering from state in JavaScript.
Task: Explain the event, update, render cycle with a small list app.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code predictionrendering from state drill
Context: I have practised rendering from state.
Task: Give me six render functions and states and ask what the page shows.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debuggingrendering from state bug
Context: Every time I add a task, all the tasks appear again underneath.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generationrendering from state practice
Context: I finished the rendering from state exercises.
Task: Create three exercises that render lists and totals from state.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code reviewrendering from state review
Context: Here is my code that uses rendering from state.
Task: Review my rendering code for duplicates, innerHTML with user data and lost listeners.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.