From 7e73e9941e7568d110ac91a7acdb3b3e0f07617c Mon Sep 17 00:00:00 2001 From: Christopher Schwarz Date: Mon, 6 Oct 2025 11:13:17 +0200 Subject: [PATCH] Optimize duplicate breakpoint detection and fix useEffect dependencies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace O(n²) filter with findIndex with O(n) Set-based duplicate detection - Add missing shouldLog dependency to useEffect array to prevent stale closures - Improve performance for larger breakpoint configurations - Maintain same functionality with better algorithmic complexity Fixes #4 --- src/BreakpointContext.tsx | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/BreakpointContext.tsx b/src/BreakpointContext.tsx index 0529620..feb6a47 100644 --- a/src/BreakpointContext.tsx +++ b/src/BreakpointContext.tsx @@ -82,9 +82,18 @@ export const BreakpointProvider: React.FC = ({ /** Check for duplicate breakpoint values */ useEffect(() => { - const duplicates = sortedBreakpoints.filter( - ([, value], index) => sortedBreakpoints.findIndex(([, v]) => v === value) !== index - ); + const seenValues = new Set(); + const duplicates: Array<[Breakpoint, number]> = []; + + for (const entry of sortedBreakpoints) { + const [, value] = entry; + if (seenValues.has(value)) { + duplicates.push(entry); + } else { + seenValues.add(value); + } + } + if (duplicates.length > 0) { if (shouldLog) { console.error( @@ -92,7 +101,7 @@ export const BreakpointProvider: React.FC = ({ ); } } - }, [sortedBreakpoints]); + }, [sortedBreakpoints, shouldLog]); // Determine the current breakpoint based on the measured width. 📏 const currentBreakpoint = useMemo(() => {