Make the media grid reflow on window resize
React · React · intermediate · modification
Makes the media grid responsive: previously the column count was computed once at mount and never updated, so resizing the window left the layout stale until a remount. Adds a resize effect that recomputes the column count from window.innerWidth on every resize and reflows the grid live. Verified by dragging the window edge — columns reflow smoothly as the width crosses each breakpoint.
ResponsiveGrid renders one album's thumbnails. Users open a different album constantly, and the grid fully unmounts and remounts each time an album is opened, so this effect runs on every album switch against the same global window object.
Requirements
- The grid picks its column count from the viewport width; recompute that count whenever the window is resized so the layout stays correct after the user resizes.
- Keep the initial render correct: the first paint must already use the column count for the current width.
- No listeners or intervals may leak across the component lifecycle: mounting and unmounting the grid repeatedly must not accumulate live handlers.
Files touched
- src/components/ResponsiveGrid.jsx
--- src/components/ResponsiveGrid.jsx
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
const GAP = 16;
export function ResponsiveGrid({ items }) {
- const [columns] = useState(() => columnsForWidth(window.innerWidth));
+ const [columns, setColumns] = useState(() => columnsForWidth(window.innerWidth));
+
+ useEffect(() => {
+ const handleResize = () => {
+ setColumns(columnsForWidth(window.innerWidth));
+ };
+ window.addEventListener('resize', handleResize);
+ }, []);
return (