Search⌘ K
AI Features

Solution: Refactored Comment Viewer App

The refactored Comment Viewer App demonstrates how small adjustments enhance React 19's rendering and performance. Key improvements include using `useTransition` for non-urgent updates, memoizing filtered comments and lists to prevent unnecessary re-renders, and implementing an external store with `useSyncExternalStore` for efficient state management. These changes lead to a more responsive UI, minimizing lag during user interactions and ensuring that components only re-render when their relevant data changes. Overall, the exercise emphasizes the importance of stabilizing derived objects and optimizing performance through careful memoization and state management strategies.

Refactored comment viewer app

The value of this exercise lies in seeing how small fixes combine to form a clearer mental model of React 19’s rendering and performance behavior. This solution walks through the final refactor, tying each change back to the symptoms observed in the broken version.

Explanation

Here’s an explanation of the code above:

  • In the App.js file:

    • Lines 6–11: Define text and a fixed comments array; comments never changes, which makes it safe and memo-friendly.

    • Line 13: The useTransition allows React to mark text updates as non-urgent, keeping the UI responsive during expensive work.

    • Line 15: The filter is wrapped in useMemo, so { query: text } is recreated only when text changes instead of every render.

    • Lines 17–21: The filteredComments is memoized; the filtered array is stable unless text or comments actually change.

    • Lines ...