const useElementMeasure = ( elRef: React.RefObject<any>, effectDeps: unknown[] = [] ) => { const [{ width, height }, setMeasure] = useState(() => { const element = elRef?.current; return { width: element ? element.clientWidth : 0, height: element ? element.clientHeight : 0, }; }); const measure = useCallback(() => { const element = elRef?.current; if (!element) { return; } setMeasure({ width: element.clientWidth, height: element.clientHeight, }); }, [elRef, ...effectDeps]); useEffect(() => { measure(); window.addEventListener("resize", measure); return () => { window.removeEventListener("resize", measure); }; }, [measure]); return [width, height]; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter