@@ -64,6 +64,7 @@ export const usePreviewRenderer = (
6464 const shadowBodySizeRef = useRef ( null )
6565 const prevEnableBackgroundRef = useRef ( null )
6666 const prevSelectedTabRef = useRef ( selectedTab )
67+ const prevSelectedNumRef = useRef ( selectedNum )
6768 const adjustAnimateFrameRef = useRef ( null )
6869 const renderedTemplate = useRef ( false )
6970
@@ -304,12 +305,31 @@ export const usePreviewRenderer = (
304305 prevSelectedTabRef . current = selectedTab
305306 } , [ selectedTab ] )
306307
308+ // Handles rendering of preview for selected patterns when category or tab changes.
307309 useEffect ( ( ) => {
308- if ( ! shouldRender ) {
310+ if ( ! shouldRender || ! content || ! shadowRoot ) {
309311 return
310312 }
311313
312- if ( ! content || ! shadowRoot ) {
314+ // Prevent unnecessary re-renders when the selection state transitions:
315+ // - If changing from unselected (0) to selected (number), or currently unselected, just update the ref.
316+ // - If changing from selected to unselected, re-rendering is handled in a separate effect to avoid duplicate renders here.
317+ if ( ( ! prevSelectedNumRef . current && prevSelectedNumRef . current !== selectedNum ) || ! selectedNum ) {
318+ prevSelectedNumRef . current = selectedNum
319+ return
320+ }
321+
322+ prevSelectedNumRef . current = selectedNum
323+
324+ if ( content ) {
325+ renderPreview ( )
326+ }
327+ } , [ selectedNum , shadowRoot ] )
328+
329+ // Effect for handling preview re-render and scale adjustment
330+ // when content, color schemes, or selection state changes (e.g., toggling from selected to unselected).
331+ useEffect ( ( ) => {
332+ if ( ! shouldRender || ! content || ! shadowRoot ) {
313333 return
314334 }
315335
0 commit comments