Skip to content

Commit

Permalink
refactor(VoiceVisualizer): replace window resize with ResizeObserver
Browse files Browse the repository at this point in the history
- Remove window resize event listener
 - Implement ResizeObserver for more accurate dimension tracking
 - Move resize logic to useLayoutEffect for synchronous measurements
 - Add proper cleanup with observer disconnect
 - Fix initial render dimensions calculation

BREAKING CHANGE: Removes window.resize event listener dependency

Closes YZarytskyi#30
  • Loading branch information
chinaza committed Feb 4, 2025
1 parent 9fad720 commit d577df9
Showing 1 changed file with 5 additions and 9 deletions.
14 changes: 5 additions & 9 deletions src/components/VoiceVisualizer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
} from "../helpers";
import { useWebWorker } from "../hooks/useWebWorker.tsx";
import { useDebounce } from "../hooks/useDebounce.tsx";
import { useLatest } from "../hooks/useLatest.tsx";
import {
BarsData,
Controls,
Expand Down Expand Up @@ -150,8 +149,6 @@ const VoiceVisualizer = ({
const index2Ref = useRef(formattedBarWidth);
const canvasContainerRef = useRef<HTMLDivElement | null>(null);

const currentScreenWidth = useLatest(screenWidth);

const {
result: barsData,
setResult: setBarsData,
Expand All @@ -165,26 +162,25 @@ const VoiceVisualizer = ({
const debouncedOnResize = useDebounce(onResize);

useEffect(() => {
onResize();
if (!canvasContainerRef.current) return;

const handleResize = () => {
if (currentScreenWidth.current === window.innerWidth) return;
setScreenWidth(window.innerWidth);

if (isAvailableRecordedAudio) {
setScreenWidth(window.innerWidth);
_setIsProcessingOnResize(true);
setIsResizing(true);
debouncedOnResize();
} else {
setScreenWidth(window.innerWidth);
onResize();
}
};

window.addEventListener("resize", handleResize);
const resizeObserver = new ResizeObserver(handleResize);
resizeObserver.observe(canvasContainerRef.current);

return () => {
window.removeEventListener("resize", handleResize);
resizeObserver.disconnect();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [width, isAvailableRecordedAudio]);
Expand Down

0 comments on commit d577df9

Please sign in to comment.