You can create a Preact component that rerenders every time the window is resized by using window.addEventListener('resize'). The general approach involves setting up an event listener in a useEffect hook, and then triggering a state update in the component whenever the resize event occurs. This will cause the component to rerender.
Source code viewer
import { h } from 'preact'; import { useState, useEffect, useRef } from 'preact/hooks'; const ResizeComponent = ({ countArray }) => { const [width, setWidth] = useState(window.innerWidth); const divRef = useRef(null); // Resize handler function const handleResize = () => { setWidth(window.innerWidth); // Ensure the ref is initialized before accessing it if (divRef.current) { // You can perform any action on the DOM element here divRef.current.textContent = `Window width is ${window.innerWidth}px`; } }; // Effect for setting up the resize event listener useEffect(() => { window.addEventListener('resize', handleResize); // Trigger the resize handler initially to set the text content handleResize(); // Cleanup the event listener on component unmount return () => { window.removeEventListener('resize', handleResize); }; }, []); // Empty dependency array means this effect runs once on mount // Effect to trigger the resize handler when countArray changes useEffect(() => { handleResize(); }, [countArray]); // Dependency array includes countArray return ( <div> <p ref={divRef}>Window Width: {width}px</p> <p>Array Count: {countArray.length}</p> </div> ); }; export default ResizeComponent;Programming Language: ECMAScript