Skip to main content
View on YouTube to comment and like!

Syntax Video

The Easiest Way to Infinite Scroll with React | Full Example

Chapter 1 0:00

Intro

infinite scroll is one of the most common patterns you see in modern apps and websites for instance on Tik Tok as you scroll the videos just keep loading same thing over on X as you scroll in your feed the posts just keep loading you can just keep scrolling forever as we sometimes do and in this video I'm going to show you how to implement this in react in a very easy way so we have here a web page which loads images from an API but then once we reach the bottom of the page it automatically makes an API requests and loads the next set of images which makes it so that we can just keep on scrolling scrolling and scrolling and scrolling so let's build this thing my name is CJ welcome to syntax to get started I generated a basic app with beat and I chose react and typescript so you can run this command give it a name and then we'll choose react typescript and then go into the directory and install all of the dependencies once the app is generated I removed everything extra so our index.

Chapter 2 0:43

Project Setup

CSS is completely blank and I have an app. TSX that just has hello world inside of it so if I run an mpm run Dev we can start it up visit it in the browser and it should just say hello world next up I'll set some basic styles on the HTML element so inside of here I'm going to select the HTML element and set the background to be a midnight blue and so that should give us a nice blue background next let's create a loading element so inside my app. TSX I'm going to create a div and then give it a class of loading and then to style it I'm going to set the width and height to 50 pixels and then I'll set the Border color so we're just going to do a 10 pixel solid border set to Gray and so I should have a nice little gray box on the screen but I want to make this a loading spinner so let's make it a circle so I'll add a border radius of 50% that should give us a nice Circle then if I set the Border top color we'll get a nice little Arc so I'll say the Border top color should

Chapter 3 1:11

Page Styles

Chapter 4 1:21

Pure CSS Loading Spinner

just be white like that and now we have a nice little uh arc on top of the circle but now I want this thing to spin cuz it's a loading spinner so I'm going to set up an animation so I'm going to add a key frames here that just is called spin and all this is going to do is just rotate 360Β° so I'm just going to say two and we'll do a transform rotate 360Β° and then on the loading element I can set its animation to be to spin and then give it a duration let's say 1 second give it an easing function and say we want it to spin forever with infinite and just like that we have a little loading spinner now let's style the parent element which contains this loading spinner and is also going to contain all of the images so I'm going to Target that main element there set it to a flex box set the flex direction to column and then do a place items of Center so by default that should just Center that on the page but because I want to have a single column of images I'm going to set a Max width here of 400

Chapter 5 2:33

Layout Styles

pixels and then a width of 100% and so by default it's going to shift it over to the left but now I want to Center that on the overall page so I'm going to set margin let's do one Rim Auto so it'll have one rim of margin around it but it'll be centered on the page itself if we look in the element inspector here we can take a look at Main and see that it actually has that margin on the edges that puts it into the center of the page and so this is where we're going to load in all of our images now to load the images from the API I'm going to use this hook called use async list and this actually comes from react stately now react stately is a library that is a part of react Spectrum which is a library that comes from Adobe and they're they're known for their very accessible component library but we can install this library and only use this hook we don't have to use their components and specifically they support infinite loading it's actually super easy to set up you can do use async list you have a function that can call your API and then return the list of elements and a curser to the next page of

Chapter 6 3:22

react-stately and useAsyncList

elements now you might have seen this implemented with something called tanack query for which is completely valid but if you're not already using tanack query in your application it's quite a bit of setup just to get access to their use infinite query hook so for one-off projects like this where you maybe you're doing like some autocomplete or infinite scroll like we're implementing here this library is really great for that so let's install it I can do an mpm install of react stately from there I'm going to copy their infinite loading example this use async list function here and then throw it at the top of my app then I need to pull in use async list from react stately go ahead and format this code with my linter so it's happy and then we can actually see this in action so by default it's just going to reach out to the Pokey API and it's going to load the first page of results so let's actually just console log our list.

Chapter 7 3:56

Why not tanstack query?

Chapter 8 4:17

Install / setup react-stately

items and then if we take a look in the dev tools whenever the page loads we should see those items that are loaded from the API so for our API we're going to be using pixels they're a stock photo website they have an API and I've actually just wrapped up their API call into a serverless function so I can hide my API key but if you want to call their API you can get an API key there and so my serverless function basically allows you to pass in a query you get back the response and then you can also pass in the page so if we pass in page two we'll get the next page of images so in the codes instead of calling the Poke API I actually want to call my serverless function here uh but I'm going to parameterize it just a little bit so first of all I'm going to pull that URL into a variable so let's just call this the base API URL I'll turn this into a template string and then I'm just going to replace this query here with just nature and our API also accepts a page parameter by default it's set to one but

Chapter 9 4:52

Pexels API Overview

Chapter 10 5:16

fetch first page of images

we can set it to one just like this now I want to work with this API in a typesafe way so one thing I can do is I can copy this Json response here and then I have an extension here in vs code called paste Json as types so if I do command shift p paste Json as types and we're going to choose typescript and I'm just going to call this the image search response that generates a nice little typescript interface here that describes the specific response that I'm getting back from the API and now that I have those types I can actually use them here so when I do res. Json right now it's just the any type but I want to set this as the image search response and now I get some type errors because it knows what properties actually exist and you can see on the type here that it actually has a photos property and that is the items that I want to pass back here so we'll just do json. photos and let's not worry about cursor for now let's just get the images loading onto the page now use async list is generic and you can see right now it has unknown

Chapter 11 5:46

Generate Types for the API Response

but I can actually tell it that this is a list that contains photos in that items array and we can actually use this type here that got generated for us so if I say use async list of photo now we can see that this list actually contains photos inside of it so now that we have this list of photo let's actually iterate over it here in our jsx so I'm just going to say lists.

Chapter 12 6:57

Creating items with the list

items. map and for each one we're going to create a div now for the key I'm going to use item. ID our API actually responds with unique IDs for each and then I'm going to give this a class name of item we're going to set that up in the CSS so if we hop over to our CSS in here we'll create an item class and I want these images to be rounded so I'm going to set the Border radius on the container here to just be 2% so we can get some nice rounded corners and then I'm going to set a background color here so I'm just going to set background and I want it to be gray but I want it to be like transparent gray so I'm going to use RGB to do that so 127 127 127 is like a standard gray but then I'm going to set an opacity of 02 I'll give it a width of 100% so it takes up the full amount of its parent container and then just so we can see these on the page I'm going to give it a height of 400 pixels and so just like that we now see a div for every image that's going to load on the page but I actually want some space between these so in the parent container because

Chapter 13 7:21

Image item styles

this is a flex box we can use the Gap property and I'm going to set the Gap to one Rim so now we should get some nice spacing between each of these and then lastly to give it some depth let's add a drop shadow so on the item class here I'm going to say filter drop shadow and the X offset I'm going to set to one rim and then the Y offset is set to one Rim so this should be like a diagonal bottom right uh drop shadow and then we can set the blur amount I'm going to set this to 1.5 rim and then I'll set the shadow color to Black and just like that we get a nice little drop shadow kind of trending towards the bottom right of each of these little images now when each of these gets added to the page I actually want them to fade in so let's add a fade in animation so down here I'm going to create a key frames for fade in and this is essentially just going to go from opacity zero to opacity one so we'll say to opacity 1 and it's coming from opacity zero and then on the item itself I'll set the animation to fade in over let's

say 2 seconds and so now when those images get added to the page they slowly fade in great now let's actually show those images I'm going to get rid of this fixed height because we're going to be setting the height dynamically in the JavaScript based on the API response because it actually includes width and height info so let's remove the height from there and then here on the image wrapper I'm going to set some inline Styles so I'm going to set the style and set the aspect ratio and I'm going to set this to item width divided by height so our API actually has that information so if I do item. width this is an actual number that our API responds with and then I can divide that by item. height what's nice about this is because I set the width to 100% now the height will automatically be calculated based on the actual aspect ratio of the original image so I don't have to set a fixed height here it'll be a dynamic height based on the width of the container because I set the aspect ratio here so if I save this we should see that some

Chapter 14 9:09

Image Container Aspect Ratio

of our images are shorter some of them are longer but now they are the perfect size to actually receive the image itself so inside the element I'll create an actual image element we'll set the source equal to item. Source you can see that the API responds with a bunch of these I'm actually just going to choose the original one and then we'll also set the alt text and the API also responds with an ALT attribute so we can set that on the image and just like that it breaks we need to set the image itself to be a width of 100% because right now it's flowing outside of that parent container so let's do that so here in the CSS I'm going to Target all images that are a child of the item class and set their width to be 100% And that looks pretty good but our border radius isn't actually showing up so on the parent container I'm going to set overflow to Hidden and then this way we actually see that border radius instead of the sharp edges of the image so pretty good we we got a nice little set

Chapter 15 10:08

Displaying the Images

of images here but now we're on to the important part which is when we reach the bottom of the page we need to actually request the next set of images and for this we're going to use intersection Observer so this is a JavaScript API that will allow us to detect when a specific element is visible in the viewport and so essentially what we want to do is when this loading spinner is visible we want to make the request for the next page of images now we could use the intersection Observer directly but it's a little bit tricky because we have to deal with refs and uh we're inside of react so there's this really great Library it's called react intersection Observer it gives us a hook called use in View and then it makes it super simple to watch a specific element to see when it's in the viewport so to use this I'll install it and then we can copy their example here and right below our use async list I'm going to say use in view we're going to bring that in from react intersection Observer and then we'll pass in some options in just a second and so really all I need to know is is the element in

Chapter 16 11:08

Intersection Observer

Chapter 17 11:33

react-intersection-observer

View and they give us this ref here which we can pass to a specific element and it'll tell us when that element is in View and the element that I care about is this loading element here so I'm just going to pass in the ref I'll say ref equals ref and now it's actually going to watch that to see when it's visible so let's actually create a use effect here and the thing that we're going to be dependent on is in View and so whenever in view changes this use effect will run and for now inside of here I'm just going to log is the element in view now before we watch this for changes I'm actually just going to remove the console log of the items so our our logs aren't cluttered up and if we go back to the browser and refresh we'll see that uh when the page loaded it was not in view and then it was in View and then it's no longer in view so because there were no images it was visible but then all of those images pushed it down so it's no longer visible and then if I scroll all the way to the bottom of the page we can see that it is now in View and so essentially whenever this gets

Chapter 18 12:15

Watching for visibility changes

set to true we now want to make a request for the next page of images now this is where that cursor property comes into play Because when the page loads we want page one that makes sense but when a user reaches the bottom of the page we want to request the next page of images so the cursor property is actually the URL that this fetch will make a request to whenever we call the load more function which I'll show you in a second so what we need to do is we need to set cursor equal to a URL that has the next page that we would like to request so it's going to look just like this but we need to change that page property here and if we take a look at the API response it actually responds with which page of results this is so in my specific use case I can actually use that data that we get back from the API to determine what the next page is going to be so right here I can say the page is json. Page Plus one so essentially whenever we call load more we're going to make the request to this next page of results so with that set up we can try

Chapter 19 13:01

Loading the next page of results

it out so inside of our use here we can say if the loading element is in view then we can say list. load more so load more is a function that they make available to us that will load the next page of results using that specific cursor they also have another built-in method called reload if we for whatever reason need to basically reset the list but for our use case we just need the load more function and you'll see my linter is yelling at me it's saying hey you're using list in this use effect you need to add it to the dependency array there's one issue with that uh which I'll show you in a second but let's actually see this happen so I'm going to log right here loading more and I'll include the current time so we can see when exactly it got called let's head back to the top of the page and refresh completely you can see that it actually makes the call to load more when the page initially loads and we don't want that so I'm actually just going to make a check to see are there any elements in the list and if not there's no reason to call load more and essentially if the list is empty that kind of means that the page has just loaded so here we'll

do uh if list. items. length as a value and and it's in view so now it's not going to call this when we first load the page because items will be an empty array and then it's going to make the request for that first page of results and then it's actually going to show that first page of images there so let's see what this does for us let's do a refresh you can see that it's still getting called twice whenever the page initially loads now one more check we can do is to see if the list itself is loading so if list. is loading that's this is a property that they make available to us if this is not true then we should call load more and at this point we're really close at this point it's still calling load more uh even though we're telling it to wait until those images have loaded and let's actually see what happens when I get to the bottom of the page so we see that it's calling the API it gets back the response but then it called load more one more time now ultimately this has to do with our dependency array here the the list

Chapter 20 15:06

Fixing duplicate load request

variable that we're getting back from use async list is changing constantly it's changing when is loading is changing it's changing when the items change basically this changes a lot depending on the underlying State and ultimately we don't want this use effect to get recreated every time the list changes we only want this to get recreated or rerun if in view changes now there are a couple of other things we could try to get this working we could try use layout effect which shouldn't actually run until the page itself has been updated and so we're essentially trying to avoid a race condition where we're not loading and the images have already been added to the page then we can check for in View and so to get around all of that I don't want this to rerun whenever list changes but if I remove it the list variable won't always be the latest value so we're going to wrap it in a ref so let's actually create a variable called list ref we're going to pull in use ref from react and then give it an initial value of the list itself and now we actually

Chapter 21 16:38

Wrapping list in useRef

want to update this ref anytime the list itself changes so I'll create a use effect here that is dependent on list and a ref has a current value that you can actually write directly to so I can say list ref. current equals list I don't have to call like a Setter method basically this setting right here doesn't trigger a rerender which is what I want I want to have access to the latest list without triggering a rerender now that I've wrapped this in a ref I can actually use the ref inside of here instead so instead of saying list I'll say list ref. current so this is always going to grab the latest value and if you don't believe me let's actually just set a log right here we'll say setting current and because this use effect is defined Above This one this use effect is always going to have access to the latest one but it's not going to get recreated if the list itself changes let's refresh you can see on the initial page load here it doesn't call loading but if I make it down to the end of the page then you can see it calls loading

more and it doesn't call it multiple times and so if I get down here and you can always see right before the call to loading more we're always setting that latest value so even though this use effect isn't dependent on the real list it's still getting access to the real one because we're using that current value of the ref but at this point we pretty much have infinite scroll it's pretty good it's pretty good but one thing we might want to do is instead of waiting until we get all the way to the bottom of the page to trigger the call for the next page of results we can actually set a root margin on the intersection Observer which will make it so that when we're a given from that specific element it'll trigger the intersection so potentially we want it to be when the the cursor is like right about here that's when we actually make the request for the next set of images so I'm going to go ahead and remove all of these logs and right here when we use the use in view function we can pass in a root margin and I'm just going to set this to 1,000 pixels so whenever that loading element is 1,000

Chapter 22 18:13

Intersection Observer rootMargin

pixels from being visible then it'll actually trigger in view to be true and that will fire off another call to our API so now if we refresh one more time let's actually just keep the network tab open so we can see the API requests you'll see that before I even reach the end it actually makes the API request and so this gives you that true infinite scroll feel where the user doesn't even see the loading image they literally just get to keep scrolling forever but behind the scenes we're actually making those requests for those next pages of results so that's it for this infinite scroll example if you want to take a look at the code follow the link down in the description and ultimately I just really wanted to show how we could combine these two libraries react stately and react intersection Observer to have a really easy infinite scroll and probably less than 20 lines of code I've seen a lot of other Solutions out there that aren't as streamlined requires a lot more code and this is definitely the simplest infinite scroll that I've seen now as you notice this

Chapter 23 19:25

Thanks!

was with just react running on the client implementing infinite scroll inside of nextjs introduces a lot of other challenges so if you want to see me implement the same example but with nextjs definitely leave a comment down below all right I'll see you in the next one [Music]

Quote it with credit and a link. Quoting Syntax