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.jsfile:Lines 6–11: Define
textand a fixedcommentsarray;commentsnever changes, which makes it safe and memo-friendly.Line 13: The
useTransitionallows React to mark text updates as non-urgent, keeping the UI responsive during expensive work.Line 15: The
filteris wrapped inuseMemo, so{ query: text }is recreated only whentextchanges instead of every render.Lines 17–21: The
filteredCommentsis memoized; the filtered array is stable unlesstextorcommentsactually change.Lines ...