React / Components and state / Lesson 7
Conditional rendering and meaningful empty states
Model loading, error, empty and populated views explicitly, with semantic feedback and stable item identity.
On this page
Lesson goals
- Choose a branch from explicit request state.
- Distinguish an empty successful result from loading or failure.
- Check accessible feedback and stable list identity.
- Model request states and select distinct loading, failure, empty, and populated views.
- Guard current-query results against obsolete responses and verify accessible recovery.
Model distinct outcomes
A result view has more than a populated list. Before data arrives, the interface may be loading; a successful response can contain zero records; a failed request needs a recoverable error. Treat these as distinct conditions rather than using an empty array to represent every outcome. Write the expected text and available action for each state. A user should not be told that no records exist while the application is still waiting for a response.
Render an empty successful result
This component receives already validated items from its parent. An early return makes the empty case visible and keeps the populated branch focused on rendering the list. Stable IDs belong to records, not positions, so React can preserve the identity of rows when the parent inserts or reorders records. The component does not fetch data or decide whether the request succeeded.
export default function Results({ items }) {
if (items.length === 0) return <p>No results yet.</p>;
return <ul>{items.map(item => <li key={item.id}>{item.label}</li>)}</ul>;
}
An empty array displays No results yet.
The parent supplies an array; zero items produce a message and nonempty items produce keyed list entries.
Communicate request progress
A parent can render a status component while it owns loading and error state. The example illustrates semantic feedback rather than claiming to fetch anything. A status region can announce progress without moving focus; an alert is appropriate only for information needing immediate attention. Avoid repeatedly mounting an urgent alert during ordinary typing, and provide a retry control when the actual operation supports retry.
export default function RequestStatus({ state }) {
if (state === "loading") return <p role="status">Loading results…</p>;
if (state === "error") return <p role="alert">Results could not be loaded.</p>;
return <p>Results are ready.</p>;
}
For loading, the status region contains Loading results….
The three branches describe loading, failure and readiness; the caller decides which state is current.
Make branch conditions explicit
JavaScript logical expressions return operands, not necessarily booleans. In JSX, using items.length && a list can render the number zero for an empty array. Prefer a boolean comparison or an early return. Keep each condition aligned with the data contract: a missing response is not automatically an empty successful response. If the source changes while a request is pending, the parent must also decide which response owns the screen.
Verify complete user paths
Exercise loading, failure, zero results and populated results using controlled input. Check the visible message and accessible announcement, then ensure a successful retry clears the previous error. Insert an item before an existing row and confirm state follows its record. Test with keyboard navigation and a screen reader where available; a role attribute by itself does not establish a complete accessible experience.
Represent the current request explicitly
An empty array alone cannot tell a user whether a request is waiting, failed, or succeeded with no matches. Model the status and the data contract together. For a simple request, an explicit status such as idle, loading, error, or success determines which view is appropriate; only a successful response with an empty array justifies a no-results message. Write a transition table before implementing the component: submitting a query starts loading, a current successful response selects success with its items, and a current failure selects error. A retry returns to loading and a later success clears the old error.
Real interfaces may retain previous results while a new request loads. If that is the chosen policy, label those results as previous or updating so the user does not confuse them with the new query. An empty initial dataset is not necessarily evidence that the current query has no matches. Decide what appears before the first search and whether stale results remain visible during refresh. These decisions belong to the owner of request state; a presentational child receiving validated items should not infer network success from an array alone.
Choose readable JavaScript branches
React uses ordinary JavaScript to choose a description. Early returns can make mutually exclusive loading, error, and empty branches easy to audit before rendering the populated list. A ternary is useful for a small two-way choice, but a long nested expression can hide precedence and missing cases. Give each branch an explicit condition and keep its message and action together. If an unknown status reaches the view, handle it according to the contract instead of silently describing it as success. Do not place conditional Hooks inside branches; Hooks must retain their call order across renders.
The && operator returns an operand rather than a guaranteed boolean. If items.length is zero, items.length && <List /> evaluates to the number zero, which React can render. Use items.length > 0 for a boolean condition or return a clear empty state first. React does not display false, null, or undefined as text children, but those values are not interchangeable with every valid domain value: zero can be a meaningful count. Choose checks that preserve zero and distinguish missing data from empty data.
Communicate progress and recovery
A user needs to know what happened and what to do next. A loading message can use a status region for nonurgent progress; a failure needing immediate attention may use an alert, but urgent announcements should not be mounted repeatedly during ordinary typing. Provide a retry control only when the owning operation supports retry, and give it an accessible name that describes the action. A successful empty search should mention the current query when useful and can offer a clear filter or create action if the product actually supports it. Avoid presenting an empty state as an error merely because no records match.
Use semantic headings, lists, buttons, and labels in each branch. A role attribute is not a substitute for testing focus, reading order, and keyboard operation. When a retry begins, replace the old error with progress according to the state model; after success, show either the new items or the successful empty message. Do not claim a request succeeded merely because a button was clicked. Keep user-entered search text when a recoverable failure occurs, and explain whether the retry repeats that same query.
Keep responses tied to the current query
Asynchronous requests can finish out of order. Suppose a search for tea starts first, then a search for coffee starts, but tea returns last. Without an ownership rule the older tea result can overwrite the newer coffee screen. Give each request an identifier or otherwise cancel and ignore obsolete work according to the application’s actual transport contract. Before committing a response, compare its identity with the current request. Cancellation alone is not proof that every old result is unable to arrive; guard state updates as well when the design requires it.
A status and its data must describe the same request. Do not display an old empty response as the result of a newer query still in progress. Error messages and retry actions also need the correct query or request identity. These lesson fixtures illustrate state decisions and do not perform network calls. A production implementation must separately define cancellation, server errors, authorization, and observability for its environment. Do not invent a fetch result or claim that a synthetic state transition contacted a service.
Verify every branch and transition
Build controlled fixtures for idle, loading, error, successful empty, and successful populated states. Assert the visible message, semantic role where appropriate, and available action for each. Test the transition from error to loading on retry, then from loading to successful empty or populated results, ensuring the old error is gone. Test zero items explicitly to catch a stray rendered zero and verify that a real count of zero can still be shown deliberately. For populated results, use stable record keys and test insertion or reordering with a local draft when identity matters.
Test a late response from an older request after a newer request becomes current; the older response must not replace the newer state under the chosen policy. Exercise keyboard retry and, where available, inspect announcements with assistive technology. Record the exact state and expected result rather than relying only on an initial screenshot. The fragments below target the course React 18.3.1 host and require JSX and a browser. They are non-runnable in this resource and their stated outcomes are predictions from synthetic inputs, not evidence of a live request.
20 worked examples
1. Idle branch
Problem: Display a prompt before any search request has started.
- The explicit idle status matches the first branch.
- No empty-result claim is made before a search has completed.
function SearchView({ status }) {
if (status === "idle") return <p>Enter a search.</p>;
return <p>Search started.</p>;
}
const view = <SearchView status="idle" />;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The view displays Enter a search.
Why this result follows: The explicit idle status matches the first branch. No empty-result claim is made before a search has completed.
2. Loading branch
Problem: Show progress while the current request has not yet finished.
- The status prop selects the loading branch.
- The view does not infer an empty success from missing data.
function Results({ status }) {
if (status === "loading") return <p role="status">Loading results…</p>;
return <p>Not loading.</p>;
}
const view = <Results status="loading" />;
Trace the stated state or interaction; no network execution is claimed.
Expected result: A status region contains Loading results….
Why this result follows: The status prop selects the loading branch. The view does not infer an empty success from missing data.
3. Failure and retry
Problem: Show a recoverable error and invoke its supplied retry action.
- The error text and action are rendered together.
- The button receives a function to invoke on activation.
function Failure({ retry }) { return <div role="alert">Could not load. <button type="button" onClick={retry}>Retry</button></div>; }
const view = <Failure retry={() => console.log("retry")} />;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The alert says Could not load and activating Retry calls the callback.
Why this result follows: The error text and action are rendered together. The button receives a function to invoke on activation.
4. Successful empty response
Problem: Distinguish a completed empty result from a loading state.
- The status identifies a successful response.
- The explicit zero length then selects its empty result branch.
function Results({ status, items }) {
if (status === "loading") return <p>Loading</p>;
if (status === "success" && items.length === 0) return <p>No matches</p>;
return <p>Other state</p>;
}
const view = <Results status="success" items={[]} />;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The view displays No matches.
Why this result follows: The status identifies a successful response. The explicit zero length then selects its empty result branch.
5. Populated success
Problem: Render two current search results as a semantic keyed list.
- The parent supplies two records for the successful view.
- map creates one list item per record with its stable id as key.
function Results({ items }) { return <ul>{items.map(item => <li key={item.id}>{item.label}</li>)}</ul>; }
const view = <Results items={[{ id: "a", label: "Tea" }, { id: "b", label: "Coffee" }]} />;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The list contains Tea followed by Coffee.
Why this result follows: The parent supplies two records for the successful view. map creates one list item per record with its stable id as key.
6. A stray numeric zero
Problem: Predict the output of a numeric length used directly with &&.
- JavaScript && returns the falsy left operand when the length is zero.
- React can render that numeric zero as a text child.
const items = [];
const view = <div>{items.length && <p>Results</p>}</div>;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The div displays 0 rather than an empty message.
Why this result follows: JavaScript && returns the falsy left operand when the length is zero. React can render that numeric zero as a text child.
7. Boolean length condition
Problem: Prevent an unwanted zero using an explicit comparison.
- The comparison evaluates to boolean false.
- React does not render false as a text child. This follows the stated input and branch contract.
const items = [];
const view = <div>{items.length > 0 && <p>Results</p>}</div>;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The div has no text or paragraph for the empty array.
Why this result follows: The comparison evaluates to boolean false. React does not render false as a text child. This follows the stated input and branch contract.
8. A deliberate zero count
Problem: Display zero when it is meaningful rather than hiding it as falsy.
- The numeric value is inserted directly as a text child.
- Zero is valid data here rather than a branch condition.
function Count({ count }) { return <p>Matches: {count}</p>; }
const view = <Count count={0} />;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The paragraph reads Matches: 0.
Why this result follows: The numeric value is inserted directly as a text child. Zero is valid data here rather than a branch condition.
9. A null missing value
Problem: Separate missing data from an explicitly empty successful array.
- The explicit null branch is evaluated before accessing length.
- Only a supplied empty array can reach the No matches branch.
function ResultSummary({ items }) {
if (items === null) return <p>Not loaded</p>;
if (items.length === 0) return <p>No matches</p>;
return <p>{items.length} matches</p>;
}
const view = <ResultSummary items={null} />;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The view displays Not loaded.
Why this result follows: The explicit null branch is evaluated before accessing length. Only a supplied empty array can reach the No matches branch.
10. Unknown request status
Problem: Handle a status outside the documented request state contract.
- Neither known branch matches paused.
- The fallback avoids silently claiming that the request succeeded. This follows the stated input and branch contract.
function View({ status }) {
if (status === "loading") return <p>Loading</p>;
if (status === "success") return <p>Ready</p>;
return <p>State unavailable</p>;
}
const view = <View status="paused" />;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The view displays State unavailable.
Why this result follows: Neither known branch matches paused. The fallback avoids silently claiming that the request succeeded. This follows the stated input and branch contract.
11. Retry starts loading
Problem: Model a retry as a transition away from the previous error.
- The transition explicitly changes the status to loading.
- It clears the previous error while retaining the query for retry.
function retry(state) { return { ...state, status: "loading", error: null }; }
const next = retry({ status: "error", error: "Offline", query: "tea" });
Trace the stated state or interaction; no network execution is claimed.
Expected result: next has status loading, error null, and query tea.
Why this result follows: The transition explicitly changes the status to loading. It clears the previous error while retaining the query for retry.
12. Successful retry with no matches
Problem: Clear an old failure when a current retry succeeds with zero items.
- The success transition replaces the request status.
- The empty array represents a successful zero-result response, not the old error.
function succeed(state, items) { return { ...state, status: "success", error: null, items }; }
const next = succeed({ status: "loading", error: "Offline" }, []);
Trace the stated state or interaction; no network execution is claimed.
Expected result: next has status success, error null, and an empty items array.
Why this result follows: The success transition replaces the request status. The empty array represents a successful zero-result response, not the old error.
13. Ignore an older response
Problem: Prevent a late response from overwriting the current search state.
- Response id 1 does not equal the current request id 2.
- The guard returns the state without applying obsolete items.
function receive(state, response) {
if (response.id !== state.requestId) return state;
return { ...state, status: "success", items: response.items };
}
const state = { requestId: 2, status: "loading", items: [] };
const next = receive(state, { id: 1, items: ["tea"] });
Trace the stated state or interaction; no network execution is claimed.
Expected result: next is the original loading state for request 2; tea is ignored.
Why this result follows: Response id 1 does not equal the current request id 2. The guard returns the state without applying obsolete items.
14. Accept the current response
Problem: Apply results only when their request identity matches the current request.
- The response id matches the currently owned request.
- The transition replaces the loading status and items with the current result.
function receive(state, response) {
if (response.id !== state.requestId) return state;
return { ...state, status: "success", items: response.items };
}
const state = { requestId: 2, status: "loading", items: [] };
const next = receive(state, { id: 2, items: ["coffee"] });
Trace the stated state or interaction; no network execution is claimed.
Expected result: next is success for request 2 with coffee as its only item.
Why this result follows: The response id matches the currently owned request. The transition replaces the loading status and items with the current result.
15. Previous results during refresh
Problem: Label retained results while a new search is still loading.
- The progress status states that the current request is unfinished.
- The heading distinguishes retained data from a completed current result.
function Refreshing({ previous }) { return <section><p role="status">Updating results…</p><h2>Previous results</h2><ul>{previous.map(x => <li key={x.id}>{x.label}</li>)}</ul></section>; }
const view = <Refreshing previous={[{ id: "a", label: "Tea" }]} />;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The view announces Updating results… and labels Tea under Previous results.
Why this result follows: The progress status states that the current request is unfinished. The heading distinguishes retained data from a completed current result.
16. Clear a filter
Problem: Offer an action that can recover from a local no-match filter.
- The empty state states that the current filter has no matching tasks.
- The button delegates the supported recovery action to its owner.
function Empty({ clear }) { return <p>No matching tasks. <button type="button" onClick={clear}>Clear filter</button></p>; }
const view = <Empty clear={() => console.log("clear")} />;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The message offers Clear filter and activating it calls clear.
Why this result follows: The empty state states that the current filter has no matching tasks. The button delegates the supported recovery action to its owner.
17. Hide an optional notice
Problem: Return no DOM content for a notice that is not applicable.
- The empty string satisfies the explicit early-return condition.
- Returning null omits the optional notice from the rendered tree.
function Notice({ message }) {
if (!message) return null;
return <p>{message}</p>;
}
const view = <Notice message="" />;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The Notice contributes no paragraph for the empty message.
Why this result follows: The empty string satisfies the explicit early-return condition. Returning null omits the optional notice from the rendered tree.
18. Two-way availability
Problem: Use a small ternary for a clear binary display decision.
- The boolean prop is false for this example.
- The ternary selects its second expression. This follows the stated input and branch contract.
function Availability({ available }) { return <p>{available ? "In stock" : "Out of stock"}</p>; }
const view = <Availability available={false} />;
Trace the stated state or interaction; no network execution is claimed.
Expected result: The paragraph reads Out of stock.
Why this result follows: The boolean prop is false for this example. The ternary selects its second expression. This follows the stated input and branch contract.
19. Stable populated rows
Problem: Preserve keyed row association when a successful result is reordered.
- The key remains the stable record id across the reorder.
- React can match the same Row among the siblings rather than matching by position.
const before = [{ id: "a", label: "Tea" }, { id: "b", label: "Coffee" }];
const after = [...before].reverse();
const rows = items => <ul>{items.map(item => <Row key={item.id} item={item} />)}</ul>;
// Edit the local draft of row a, then render rows(after).
Trace the stated state or interaction; no network execution is claimed.
Expected result: The a row moves after b and retains its local draft if Row remains mounted with the same type and key.
Why this result follows: The key remains the stable record id across the reorder. React can match the same Row among the siblings rather than matching by position.
20. Preserve query on failure
Problem: Keep the submitted query available for a retry after a synthetic failure.
- The transition changes status and error while spreading existing fields.
- The retained query lets the owner define retry for the same search.
function fail(state, message) { return { ...state, status: "error", error: message }; }
const next = fail({ status: "loading", query: "tea", items: [] }, "Offline");
Trace the stated state or interaction; no network execution is claimed.
Expected result: next has status error, query tea, and error Offline.
Why this result follows: The transition changes status and error while spreading existing fields. The retained query lets the owner define retry for the same search.
Common errors and fixes
A zero appears instead of an empty message.
- Why it happens
- A numeric length is returned by a logical expression.
- How to fix it
- Use an explicit comparison or early return.
- Prevent it next time
- Exercise the zero-item case in a rendered test.
The empty message appears before a request finishes.
- Why it happens
- Loading and successful empty results share one representation.
- How to fix it
- Track request status separately from its data.
- Prevent it next time
- Write a transition table before implementing the view.
A row retains another record’s draft after reordering.
- Why it happens
- The list key represents position instead of record identity.
- How to fix it
- Use a durable unique record ID.
- Prevent it next time
- Include insertion and reordering in interaction tests.
20 practice exercises
1. A search returns an empty array while a second search is still pending. What should the interface show?
Show hint
Associate the visible status and any response with the current search identity.
Show worked solution
Represent the pending request independently and show loading for the current search. Show an empty result only after the current request succeeds with zero items. Ensure a late earlier response cannot overwrite the current search state.
Show loading for the second search while it remains pending. An empty result from an earlier search does not establish the current outcome. Apply a response only if it belongs to the current request; after that request succeeds with zero items, show the successful empty state.
Check your solution
- The current pending search displays loading.
- A late earlier empty response cannot replace current state.
2. Why can a list branch using items.length && list show an unexpected zero?
Show hint
Evaluate the JavaScript && expression when the length is zero.
Show worked solution
The logical operator returns its first falsy operand, which is the number zero. React can render that number. Compare the length with zero explicitly or return the empty state before rendering the list.
With an empty array, items.length is numeric 0 and && returns that falsy operand. React can render 0, so use items.length > 0 for a boolean condition or return the empty message before the list. Preserve zero when it is an intended count.
Check your solution
- The explanation identifies numeric zero as the returned operand.
- The repair uses a boolean comparison or an early empty return.
3. A search has not yet been submitted. Choose a useful view without claiming there are no matches.
Show hint
Give the pre-search state a distinct identity.
Show worked solution
Represent the state as idle and show a prompt such as Enter a search. Do not use an empty result message until the current request succeeds with zero items. Verify that the initial view contains the prompt and no claim about completed results.
Check your solution
- The initial status is idle.
- The view does not claim a completed empty search.
4. A current request is loading with an empty initial array. Choose the correct message and explain why.
Show hint
Status determines whether the empty array is a result.
Show worked solution
Show a loading message or status region while the current request remains pending. The empty initial array does not prove that the request succeeded with no matches. Only after the current request succeeds should its zero-item response select the empty-result branch.
Check your solution
- The loading branch is visible.
- No-results text is not shown as a completed result.
5. A request succeeds with no records. Create an empty-state message and explain its distinction from failure.
Show hint
A successful empty array is a valid outcome.
Show worked solution
For status success and items.length === 0, render a message such as No matches. This reports a completed query with no records rather than a failed request. Offer a clear-filter action only if the application actually supports it and preserve the query context.
Check your solution
- Success with zero items displays No matches.
- The state is distinct from an error.
6. A request fails while searching for "tea". Specify feedback and a retry that preserves the query.
Show hint
Keep the error and query under the request owner.
Show worked solution
Show a clear failure message and a native Retry button when retry is supported. Retain tea as the current query; activating Retry moves to loading and repeats that query under the owner’s operation contract. Do not report success until a current response confirms it.
Check your solution
- The error is visible with a Retry action.
- Retry retains the tea query and starts loading.
7. A successful response contains Tea and Coffee with ids a and b. Render a semantic result list.
Show hint
Map records to li elements with stable id keys.
Show worked solution
Render <ul>{items.map(item => <li key={item.id}>{item.label}</li>)}</ul> for the populated success branch. The resulting list displays Tea followed by Coffee. Stable ids let React match rows if the same records later reorder or a new item is inserted.
Check your solution
- The list contains Tea and Coffee.
- The direct siblings use keys a and b.
8. Explain why items.length && <List /> displays zero for an empty collection, and repair it.
Show hint
JavaScript && returns an operand rather than always returning a boolean.
Show worked solution
When length is zero the expression returns numeric 0, and React renders that number. Use items.length > 0 && <List /> to omit the list or return a separate empty message first. Test an empty array so the unintended zero cannot go unnoticed.
Check your solution
- The original expression returns numeric 0.
- The repaired condition returns false for an empty array.
9. A count of zero is valid data. Render it without treating zero as a missing value.
Show hint
Insert the number directly as a child.
Show worked solution
Use <p>Matches: {count}</p> with count={0}; the result reads Matches: 0. Do not write count && <p>Matches: {count}</p> when the number itself is meaningful. Use an explicit null or undefined check if missing counts need a different branch.
Check your solution
- The visible count is 0.
- Missing data is checked independently of zero.
10. A component receives null before data loads and [] after a successful empty response. Design distinct branches.
Show hint
Check null before accessing the array length.
Show worked solution
Return Not loaded for items === null, then No matches when items.length === 0, and render the list otherwise. This prevents a null length error and preserves the distinction between absent data and a valid empty array. The parent remains responsible for request status.
Check your solution
- Null displays Not loaded.
- An empty array displays No matches.
11. A view receives an unexpected status "paused". Choose a safe fallback rather than silently claiming success.
Show hint
Handle unknown values explicitly under the component contract.
Show worked solution
Provide an explicit fallback such as State unavailable or reject the unexpected value at the boundary. Do not let an unconditional final branch say Results ready for any unknown status. Log or diagnose the invalid state according to the application’s real observability policy.
Check your solution
- Paused does not produce a success claim.
- The unexpected state has a defined handling path.
12. A request fails, the user retries, and the retry starts. Describe the state transition and visible feedback.
Show hint
Move from error to loading and clear the old error.
Show worked solution
On retry set status to loading and clear the previous error while retaining the intended query. Show progress and disable or otherwise manage duplicate retry interactions according to policy. If the current retry later succeeds, replace loading with its result rather than keeping the old error.
Check your solution
- The retry transition enters loading.
- The old error is cleared from the active state.
13. A retry succeeds with an empty array after an error. Predict the next state and message.
Show hint
Success with zero items is not the previous failure.
Show worked solution
Set status to success, clear the error, and store the empty items array from the current request. The view then displays its successful No matches message. Verify that neither the prior error nor the loading message remains as the active branch.
Check your solution
- The final status is success with zero items.
- The previous error is no longer displayed.
14. Search request 1 for tea returns after request 2 for coffee has become current. Specify the ownership check.
Show hint
Compare the response identity with the current request identity.
Show worked solution
Before applying the response, compare its id with the current request id. Because 1 differs from 2, ignore the tea response and keep request 2’s current state. Cancellation can complement this guard but should not be assumed to make every obsolete completion impossible.
Check your solution
- The late response for request 1 is ignored.
- Request 2 retains ownership of the screen.
15. A response for current request 7 contains one item. Describe the valid transition from loading.
Show hint
Match the response to the currently owned request before updating state.
Show worked solution
When the response id equals current request id 7, set status to success and replace items with that response’s item. Clear any previous error according to the state model. A response for a different id must not perform the same transition.
Check your solution
- Request id 7 is verified before applying the result.
- The current result is displayed as a success.
16. An interface keeps old results while a new query loads. Explain how to avoid misleading the user.
Show hint
Label both the ongoing request and the age of the visible data.
Show worked solution
Show an updating status and identify the displayed rows as previous results, or choose to hide them until the new response arrives. Do not label the previous list as the completed result of the new query. Test the transition to the new response, including zero matches.
Check your solution
- The ongoing request is communicated.
- Previous rows are not presented as current completed results.
17. A no-match filter can be cleared locally. Design a keyboard-accessible recovery action.
Show hint
Use a native button with a meaningful action name.
Show worked solution
Show a message such as No matching tasks and a <button type="button">Clear filter</button> wired to the owner’s clear callback. Verify keyboard activation and that clearing the filter restores the appropriate task view. Only offer this action when the feature exists.
Check your solution
- The button has the accessible name Clear filter.
- Activation invokes the supported clear action.
18. A notice is optional and receives an empty message. Choose a branch that renders no notice element.
Show hint
An early return can return null.
Show worked solution
Return null when the message is empty and return a paragraph containing the message otherwise. For the empty input there is no notice paragraph; for "Saved" the paragraph reads Saved. Use this for optional content rather than hiding a meaningful zero count.
Check your solution
- An empty message creates no notice paragraph.
- A nonempty message appears as text.
19. A results component shows a conditional list. Explain where its Hooks should be called.
Show hint
Hook call order must remain consistent across renders.
Show worked solution
Call any needed Hooks unconditionally at the top level of the component before its early returns, or move branch-specific behavior into separate components. Do not call a Hook only in the success branch because switching status would change the order of Hook calls.
Check your solution
- Hooks are not called conditionally.
- Branch changes preserve the component’s Hook order.
20. Design a test covering loading, error, retry, and successful empty results for one query.
Show hint
Control the states or synthetic responses and verify each transition.
Show worked solution
Start the query and assert loading, provide a failure and assert its message and Retry control, then activate retry and assert loading again. Resolve the current retry with an empty array and assert No matches while the old error is absent. Verify keyboard operation of Retry.
Check your solution
- Retry removes the active error and shows loading.
- Current empty success shows No matches without the old error.
Key takeaways
- Model loading, error, empty and populated results separately.
- Use semantic feedback and stable record keys.
- Verify the whole user path with controlled states.
- An empty array is not evidence of successful completion without request status.
- Use explicit boolean conditions when zero should not become rendered text.
- Associate responses and retry actions with the current request and query.