Skip to content

Keyed x-for with seems to not be robust against adding/removing elements #4843

Closed

Description

@mikejsavage

Alpine.js version

v3.15.12

Browser and operating system

Safafi/Vivaldi (chrome) on macOS, Chrome on Windows

Describe the issue you're experiencing

I am trying to implement virtual scrolling on a large photo album. My approach is to make a div sized to the height of the full album, and put another div inside that with its top set to slightly above the window scroll region and render a subrange of the images inside that.

Or in slightly simplified code:

<div :style="{ height: height }">
        <div :style="{ top: top }" @scroll.window="UpdateLayout()">
            <template x-for="i in visible_end - visible_start">
                <img src="photos[visible_start + i - 1]">
            </template>
        </div>
</div>

This works fine, except that Alpine reuses img tags, and if you change an img's src it will show the old image (thumbnail in this case) until the new one has fully loaded, which is visibly janky while scrolling the page.

I believe the standard fix for this is to add :key=visible_start + i to force Alpine to create new elements, which it does, but it also seems like Alpine gets confused by the additions/removals and eventually messes up the page.

Code snippets to reproduce the issue

See this PoC: https://mikejsavage.co.uk/alpinejs.html

Scroll around for a bit and you will notice that 1) all the elements can "jump" up or down when they shouldn't and 2) sometimes elements get duplicated, most obviously sometimes if you scroll all the way back to the top the first row gets duplicated. If you remove :key in the inspector it all works as intended.

Screenshots/screen recordings

Screen.Recording.2026-06-14.at.10.00.24.am.mov

How do you expect it to work?

.

Please confirm (incomplete submissions will not be addressed)

  • I have provided easy and step-by-step instructions to reproduce the bug.
  • I have provided code samples as text and NOT images.
  • I understand my bug report will be removed if I haven't met the criteria above.

Activity

  1. joshhanley commented on Jun 14, 2026

    @joshhanley
    Collaborator

    @mikejsavage thanks for reporting! Can you please provide code for a simple reproduction that we can copy to our machines to investigate? Thanks!

  2. mikejsavage commented on Jun 15, 2026

    @mikejsavage
    Author

    https://mikejsavage.co.uk/alpinejs.txt is self contained besides <script defer src="./alpine-3.15.12.js"></script> and can be opened as a file. The relevant code is 7 lines at the end

  3. joshhanley commented on Jun 15, 2026

    @joshhanley
    Collaborator

    @mikejsavage please just paste the code here in code blocks. Thanks!

  4. mikejsavage commented on Jun 15, 2026

    @mikejsavage
    Author
    <script defer src="./alpine-3.15.12.js"></script>
    
    <style>
    .grid {
    	position: relative;
    	display: grid;
    	grid-template-columns: repeat( auto-fill, minmax( 6cm, 1fr ) );
    	gap: 0.2rem;
    	padding: 0.5rem;
    }
    
    span {
    	aspect-ratio: 1;
    	width: 100%;
    	border: 1px solid #333;
    	display: flex;
    	align-items: center;
    	justify-content: center;
    	font-size: 3rem;
    }
    </style>
    
    <script>
    const getSHA256Hash = async (input) => {
    	const textAsBuffer = new TextEncoder().encode(input);
    	const hashBuffer = await window.crypto.subtle.digest("SHA-256", textAsBuffer);
    	const hashArray = Array.from(new Uint8Array(hashBuffer));
    	const hash = hashArray
    		.map((item) => item.toString(16).padStart(2, "0"))
    		.join("");
    	return hash;
    };
    
    async function hashStringToColor(str) {
    	var hash = await getSHA256Hash(str);
    	return "#" + hash.substr( 0, 6 );
    }
    
    document.addEventListener( "alpine:init", () => {
    	Alpine.data( "photos", () => ( {
    		height: 0,
    		top: 0,
    		visible_start: 0,
    		visible_end: 0,
    
    		fullscreen: null,
    
    		StripPx( size ) {
    			return size.replace( /px$/, "" );
    		},
    
    		GridSpec() {
    			let cols = window.getComputedStyle( document.querySelector( ".grid" ) ).gridTemplateColumns.split( " " );
    			let gap = window.getComputedStyle( document.querySelector( ".grid" ) ).gap;
    			return {
    				cols: cols.length,
    				row_height: parseFloat( this.StripPx( cols[ 0 ] ) ),
    				gap: parseFloat( this.StripPx( gap ) ),
    			};
    		},
    
    		UpdateLayout() {
    			const grid = this.GridSpec();
    
    			const top = window.visualViewport.pageTop - window.visualViewport.height * 0.5;
    			const bottom = window.visualViewport.pageTop + window.visualViewport.height * 1.5;
    
    			const row_height = parseFloat( grid.row_height ) + parseFloat( grid.gap );
    
    			const cells = 10000
    
    			const last_row = Math.ceil( cells / grid.cols );
    			const top_row = Math.max( 0, Math.min( last_row, Math.floor( top / row_height ) ) );
    			const bottom_row = Math.min( last_row, Math.ceil( bottom / row_height ) );
    
    			this.visible_start = Math.min( cells, top_row * grid.cols );
    			this.visible_end = Math.min( cells, bottom_row * grid.cols );
    
    			this.height = ( grid.row_height * last_row + grid.gap * Math.max( 0, last_row - 1 ) ) + "px";
    			this.top = ( grid.row_height * top_row + grid.gap * Math.max( 0, top_row - 1 ) ) + "px";
    		},
    	} ) );
    } );
    </script>
    
    <div x-data="photos" :style="{ height: height }">
    	<div class="grid" :style="{ top: top }" x-init="UpdateLayout()" @scroll.window="UpdateLayout()" @resize.window="UpdateLayout()">
    		<template x-for="i in visible_end - visible_start" :key="visible_start + i">
    			<span x-text="visible_start + i" :style="{ background: await hashStringToColor( ( visible_start + i ).toString() ) }"></span>
    		</template>
    	</div>
    </div>
  5. mikejsavage commented on Jun 15, 2026

    @mikejsavage
    Author

    As an immediate workaround or in case this isn't actually a bug, <template x-for="i in Array.from( { length: visible_end - visible_start }, ( _, i ) => visible_start + i )" :key="i"> seems to work

  6. joshhanley commented on Jul 1, 2026

    @joshhanley
    Collaborator

    @mikejsavage thanks for that! I've submitted a PR #4851 with a fix.

  7. self-assigned this
    on Jul 1, 2026
  8. mikejsavage commented on Jul 1, 2026

    @mikejsavage
    Author

    Great, thanks!

  9. calebporzio commented on Jul 4, 2026

    @calebporzio
    Collaborator

    Thanks for the great repro @mikejsavage — this one was subtle. Confirmed on main: with :key="visible_start + i", when the visible window shifts, reused keyed elements can render with a stale loop scope. In my repro (window shifting from 1–15 to 13–30), the first reused rows rendered 25, 26, 27 where 13, 14, 15 should be — stale i plus the new visible_start — which is also why you saw rows duplicated further down.

    The root cause is in the scheduler: an effect that already ran earlier in the same flush couldn't be re-queued, so after x-for refreshed the reused element's scope, its x-text never re-ran. I verified @joshhanley's fix in #4851 against this exact scenario and it resolves it — same repro passes on that branch. Your Array.from workaround is a solid stopgap until that lands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions