Skip to content

How to implement infinite scroll with Phoenix LiveView

Subscribing to scroll events can cause performance and concurrency issues because when scrolling, hundreds of events can be triggered.
A performant way to react to scroll events is the Interaction Observer.

The Interaction Observer observes if an element is visible within another element. In this case a element is added to the end of the list. When it becomes visible inside of the window element, a "load more" event is triggered.

Phoenix LiveView

In the template, add an HTML element after the list. The position of the element will be observed within the window.

defmodule DemoWeb.UserLive.IndexAutoScroll do
use Phoenix.LiveView
alias DemoWeb.UserLive.Row
def render(assigns) do
<tbody id="users" phx-update="append">
<%= for user <- @users do %>
<%= live_component @socket, Row, id: "user-#{}", user: user %>
<% end %>
<div phx-hook="InfiniteScroll" data-page="<%= @page %>"></div>
def mount(_params, _session, socket) do
|> assign(page: 1, per_page: 10)
|> fetch(), temporary_assigns: [users: []]}
defp fetch(%{assigns: %{page: page, per_page: per}} = socket) do
assign(socket, users: Demo.Accounts.list_users(page, per))
def handle_event("load-more", _, %{assigns: assigns} = socket) do
{:noreply, socket |> assign(page: + 1) |> fetch()}

Javascript Hook

This hook initializes an Interaction Observer and triggers a "load-more" event once the added element becomes visible within the window.

export const InfiniteScroll = {
page() {
loadMore(entries) {
const target = entries[0];
if (target.isIntersecting && this.pending == {
this.pending = + 1;
this.pushEvent("load-more", {});
mounted() {
this.pending =; = new IntersectionObserver(
(entries) => this.loadMore(entries),
root: null, // window by default
rootMargin: "0px",
threshold: 1.0,
beforeDestroy() {;
updated() {
this.pending =;

Use the hook like any other hook in LiveView.

import {InfiniteScroll} from "./infinite_scroll"
// ...
let liveSocket = new LiveSocket("/live", Socket, {hooks: {InfiniteScroll}, params: {_csrf_token: csrfToken}})


  • Elixir Forum How can I implement an infinite scroll in liveview?
  • Mozilla developer Interaction Observer API


These notes are unpolished collections of thoughts, unfinished ideas, and things I want to remember later. In the spirit of learning in public, I'm sharing them here. Have fun exploring, if you want!
© 2022 by Adrian Philipp