JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 14: State and PersistenceLesson 67 of 150About 45 minutes

Lesson 67: Rendering interfaces from state

01Opening question

After the state changes, which parts of the page need updating? What if you just redrew all of it?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

render reads the state and rebuilds the list. Call it after every change and the page always matches the data.

const state = { items: ["Tea", "Mug"] };
function render() {
  const list = document.querySelector("#list");
  list.replaceChildren(...state.items.map((name) => {
    const li = document.createElement("li");
    li.textContent = name;
    return li;
  }));
}
render();
state.items.push("Spoon");
render();
console.log(document.querySelector("#list").children.length);

03Objective and prerequisites

Learning objective: Write render functions that build the interface from state, re-render after every change, and escape user content safely.

You need: Lesson 66: Understanding application state, Lesson 54: Creating and removing elements

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.

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.

Open the full glossary

06Visual learning object

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.

Loading the interactive object…

Open the full State-to-interface rendering explorer page with its guided experiment.

07Examples

ex-067-01Event → update → render Browser page (sandboxed preview)

The listener changes state and calls render; render never changes state.

const state = { tasks: ["Plan"] };
const tasks = document.querySelector("#tasks");
function render() {
  tasks.replaceChildren(...state.tasks.map((t) => {
    const li = document.createElement("li");
    li.textContent = t;
    return li;
  }));
}
document.querySelector("#add").addEventListener("click", () => {
  state.tasks.push("Task " + (state.tasks.length + 1));
  render();
});
render();
document.querySelector("#add").click();
document.querySelector("#add").click();
console.log([...tasks.children].map((li) => li.textContent).join(" | "));
Sample input
None
Expected output
Plan | Task 2 | Task 3

A list: Plan, Task 2, Task 3

Common mistake
Appending a new li in the click handler and also calling render, which duplicates items.
Try this
Add a Clear button that empties the state.
Source
examples/ex-067-01-render-loop.js

ex-067-02Safe rendering of user text Browser page (sandboxed preview)

textContent shows text; innerHTML would run it as markup.

const comments = ["Nice!", "<img src=x onerror=alert(1)>"];
const list = document.querySelector("#comments");
list.replaceChildren(...comments.map((c) => {
  const li = document.createElement("li");
  li.textContent = c;
  return li;
}));
console.log(list.querySelectorAll("img").length, list.lastElementChild.textContent.length);
Sample input
None
Expected output
0 28
Common mistake
Building rows with innerHTML and template strings that include user comments.
Try this
Write an escapeHTML function and compare.
Source
examples/ex-067-02-escape.js

ex-067-03Rendering derived values Browser page (sandboxed preview)

render can compute what to show: counts, empty states and filtered items.

const state = { todos: [{ t: "Read", done: true }, { t: "Cook", done: false }], showDone: false };
function render() {
  const visible = state.todos.filter((x) => state.showDone || !x.done);
  document.querySelector("#summary").textContent = visible.length ? visible.length + " shown" : "Nothing to show";
  document.querySelector("#list").replaceChildren(...visible.map((x) => Object.assign(document.createElement("li"), { textContent: x.t })));
}
render();
console.log(document.querySelector("#summary").textContent, document.querySelector("#list").textContent);
state.showDone = true;
render();
console.log(document.querySelector("#summary").textContent, document.querySelector("#list").textContent);
Sample input
None
Expected output
1 shown Cook 2 shown ReadCook
Common mistake
Storing the filtered list in state as well as the full list.
Try this
Show "Nothing to show" when every todo is done and hidden.
Source
examples/ex-067-03-derived-view.js

ex-067-04Keeping elements by key Browser page (sandboxed preview)

Reusing elements by id keeps focus and typed text across renders.

const rows = document.querySelector("#rows");
const byId = new Map();
function render(items) {
  rows.replaceChildren(...items.map((item) => {
    let li = byId.get(item.id);
    if (!li) {
      li = document.createElement("li");
      byId.set(item.id, li);
    }
    li.textContent = item.name;
    return li;
  }));
}
render([{ id: 1, name: "A" }, { id: 2, name: "B" }]);
const first = rows.firstElementChild;
render([{ id: 2, name: "B" }, { id: 1, name: "A*" }]);
console.log(rows.lastElementChild === first, rows.textContent);
Sample input
None
Expected output
true BA*
Common mistake
Rebuilding a list of inputs from scratch while someone is typing in one.
Try this
Remove map entries for ids that disappear.
Source
examples/ex-067-04-keyed.js

08Guided exercises

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");

More cases in the Debugging Detective Laboratory

11Practical scenario

Frameworks under the hood

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.

const view = (state) => state.items.map((i) => "<li>" + i + "</li>").join("");
console.log(view({ items: ["a", "b"] }));

12Knowledge check

1. What does a render function do?

  • Change state
  • Make the page match the current state
  • Fetch data
  • Add listeners

2. Why do items appear twice after every update?

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

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

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.

16AI learning prompts

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 explanation rendering 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 prediction rendering 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.
Debugging rendering 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 generation rendering 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 review rendering 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.