Web Development Pro | Lesson 036 | State and Derived Views
Web Development Pro · Lesson 36 of 60
Module 4: Data, modules, and state
In this lesson
Prerequisites and learning outcomes
Complete lesson 35 first. This lesson builds on single-source state and deterministic rendering. By the end, you can derive filters, counts, and selected content from one explicit state object. Plan 10–15 minutes for the core explanation and additional time for the worked practice.
Give the interface one source of truth
The directory now combines loaded records, a search query, and a category filter. If you separately store visible records, a count, and an empty-state flag, those copies can disagree after one update is missed. Store the essential state and derive the view from it. The count should come from the visible collection, and the empty state should come from that count.
A useful state object describes what the application currently knows or intends. It is not simply a copy of every DOM attribute. The DOM displays state and receives user input; it should not become an accidental database whose text must be parsed to discover the selected category or number of records.
Define a small state contract
This lesson uses items, query, and category. Items are validated workshop records. Query is a string. Category is all, repair, or textiles. The helper creates a new state object when filters change, preserving the original records and making the transition easy to inspect.
File state.mjs:
export function createState(items) {
return { items, query: '', category: 'all' };
}
export function setFilters(state, query, category) {
const allowed = ['all', 'repair', 'textiles'];
return {
...state,
query: query.trim().slice(0, 100),
category: allowed.includes(category) ? category : 'all'
};
}
export function selectVisible(state) {
const term = state.query.toLowerCase();
return state.items.filter(item =>
(state.category === 'all' || item.category === state.category) &&
item.title.toLowerCase().includes(term));
}
The query limit keeps this small demo's filter state bounded and matches the input's maxlength. Unknown categories normalize to all rather than creating an unexplained empty selection. These are explicit product rules. A different application could reject unknown categories, but its URL, form, and state helpers should agree on that policy.
Derive related output together
After selecting visible items, render their rows, use visible.length for the count, and show the empty message only when that length is zero. Do not calculate the count from all records while rendering a filtered subset. A count that disagrees with the visible list damages trust even if both calculations are individually valid for different questions.
Derived values can be calculated on demand for this small dataset. Caching them prematurely adds invalidation work without a demonstrated performance need. If a larger application needs memoization, define which inputs make the cached result stale and test that behavior. “Stored somewhere” is not a performance strategy by itself.
A selection such as an opened workshop can use a stable id rather than copying the entire record into another state field. Then the current record can be derived from items. If filtering hides that record, decide whether the selection remains or clears. State design should expose that policy instead of leaving a stale detail panel by accident.
Separate a committed filter from a draft field
A user may type into a search field without submitting yet. The input's current value is a draft; the state query can represent the last applied search. If an asynchronous reload finishes while the user is typing, a general render should not overwrite that draft with the older committed query. Synchronize controls deliberately at initialization, submission, reset, or history navigation.
This lesson's simple example applies filters on submit. The handler reads the controls, calls setFilters, normalizes the control values to the committed state, and renders. Data-only updates can render the results without rebuilding the controls. Keeping those responsibilities separate preserves focus and unfinished input.
Do not attach listeners inside render. The event wiring is stable setup; state transitions happen in handlers; rendering projects the resulting state. This one-directional sequence is easier to debug than handlers that partly change text, partly edit records, and partly infer their next action from old DOM content.
Preserve the input contract
SetFilters expects a string query because the browser input value is a string and URL parsing will also provide a string. A function's contract should be explicit even when it does not revalidate every internal call. External JSON records are validated before entering items, while internal state helpers can rely on that established boundary.
The spread update creates a new outer state object and reuses the items array because this operation does not change the records. This is intentional sharing. It is not a deep clone, and callers should not mutate items through either state reference. The test checks that the prior query and category remain unchanged after creating the next state.
Test transitions and derived views
Use a three-record fixture with two repair workshops and one textiles workshop. All plus an empty query yields three; repair yields two; repair plus bicycle yields one; textiles plus bicycle yields zero. These cases check the conjunction between filters rather than testing each filter in isolation only.
Also test whitespace normalization, case-insensitive matching, an unknown category, and a query longer than the documented limit. Verify the original state remains unchanged and the new state retains the original items reference. This distinguishes intentional structural sharing from accidental mutation.
The complete example displays a list and count through the limited renderer fixture, while the pure helper tests run directly in Node. Browser keyboard, focus, and visual checks remain unrun in the authoring environment. State consistency is a valuable tested property, but it does not automatically establish the usability of every interface state.
Worked practice
Worked exercise 1: Repair a mismatched count
Task: A repair filter displays two rows but the count says three. Worked answer: derive both rows and count from the same visible array returned by selectVisible. The total source length answers a different question and should not be labeled as the current result count.
Worked exercise 2: Preserve a draft during reload
Task: A data refresh resets a half-typed search to the last submitted query. Worked answer: keep control synchronization separate from result rendering. A data-only render should not overwrite the input draft unless the product explicitly intends that behavior and communicates it.
Worked exercise 3: Combine filters
Task: Category is textiles and the query is bicycle. Worked answer: no record matches both conditions, so the derived view has zero rows. Using OR instead of AND would produce unrelated records and violate the stated combined-filter rule.
Knowledge check
Question 1
Where should the displayed result count come from? A) The derived visible collection. B) The unfiltered source length regardless of filters. C) The input array length before the category condition is applied. D) A stored count updated only when the query changes.
Check question 1: answer and explanation
Answer: A. Related view elements should share one derivation.
Question 2
What does the new state share in this filter update? A) The prior state object with its query reassigned. B) The unchanged items array reference. C) A separately cloned items array for every filter change. D) A copied count field that is independent of the visible records.
Check question 2: answer and explanation
Answer: B. Structural sharing is deliberate because records are not changed.
Question 3
Why distinguish draft input from committed state? A) The current input value always equals the last applied filter. B) A data reload should commit whatever text is currently being typed. C) Background updates should not erase unfinished typing. D) Every render should reset controls from the committed state.
Check question 3: answer and explanation
Answer: C. Different update triggers need different control-synchronization policies.
Question 4
How are category and query combined here? A) Either condition alone is enough. B) Query overrides category entirely. C) Category is ignored when query exists. D) Both conditions must match.
Check question 4: answer and explanation
Answer: D. The predicate uses conjunction to narrow the result set.
Question 5
What does creating a new outer state object guarantee? A) The previous outer fields are not reassigned by that update. B) Every nested value is deeply cloned. C) All future mutations are impossible. D) The browser focus is preserved automatically.
Check question 5: answer and explanation
Answer: A. Nested references remain shared unless explicitly copied.