Is Next.js 15 any good? "use cache" API first look
- Views
- 168K
- 168,325
- Outlier
- ×0.5
- Median 316K
- Length
- 8:16
- Published
- Nov 27, 2024
- Wednesday
- Comments
- 317
- 6.4K likes
Script
How it's written
- Words
- 1,828
- Words a minute
- 221
- Reading time
- 8 min
- Segments
- 6
The hook
0:00–0:26there are only two hard problems in computer science naming things cash invalidation and off by one errors maybe you've heard that joke before because another problem with programming is that we only have one joke and it's not very funny but there is some truth in the original joke and that's the fact that caching can be extremely difficult and the nextjs JavaScript framework is the poster child for these modern challenges a few weeks ago forcell released nextjs 15 and it comes with all kinds of
Structure
there are only two hard problems in computer science naming things cash invalidation and off by one errors maybe you've heard that joke before because another problem with programming is that we only have one joke and it's not very funny but there is some truth in the original joke and that's the fact that caching can be extremely difficult and the nextjs JavaScript framework is the poster child for these modern challenges a few weeks ago forcell released nextjs 15 and it comes with all kinds of awesome new features like tools to automatically migrate code a fast turbo pack Dev server and a new API to run code in the background after a request is complete but the biggest change is that they totally overhaul the way caching works and to be honest it's pretty awesome and that's what we'll look at in this video by default everything is cached in xjs like a server component that defines a web page and also any calls you make to the fetch function would be cached by default to try to optimize performance by preventing the server from doing extra work and rendering the same page over and over again the problem is that in some cases you might have multiple data fetching operations to render a page you might want some of them to be cashed but you might want others to be revalidated on every request and opting out of the cash could be pretty annoying there's a few different ways to do it like adding the Cache no store option to fetch or by exporting this Force Dynamic variable or by setting the cach control headers manually it's kind of a mess and easy to run into problems where your data is not updating because it's being cached and you have no idea why the good news is that in X15 things are becoming far more intuitive with a new API called Dynamic IO which allows you to cash or not cash
Watch from 0:00anything while also simplifying your code and making it far more explicit to demonstrate how this works let's look at some code I'm here in a brand new nextjs project but currently this feature is experimental so let's enable it by adding Dynamic IO to the next config and as of today we'll also need to be on the nextjs canary version which you can update to with these commands and optionally you'll notice that I'm using Dino here instead of nodejs because they have some cool utilities that we'll look at later but that's totally optional if you want to learn more about you know my full course is now available and I also just updated my nextjs course and if you're watching this before December 1st 2024 you can use the Black Friday discount to get access to everything at 40% off but now let's take a look at the new caching system in nextjs let's imagine we have an application that needs to display a product description and price to simulate that I've created this utility here that has a separate function for get product and get price I'm using the library Faker JS to generate some fake data which you can think of as data you would fetch from a database interesting backstory on Faker JS a few years ago the original developer intentionally corrupted this project to break a bunch of people's apps on purpose as a statement against open source abuse and lack of funding it actually made it into the mainstream news and was the story that motivated me to start the code report series on the main Channel ultimately it didn't work out too well for him and they took over the project and now it's maintained by someone else in this demo Faker JS is really useful because it makes it easy to tell which data is cached and which is not now from there I'm creating a page on the store Route inside of which we have a server component inside that
Watch from 1:31component we get the product and price synchronously and then render it in the HTML if we go ahead and serve the application you'll notice in the browser that every time I refresh the page I'm getting a new product price in description that's because currently this page is not cach and nextjs will render every time we refresh but now let's make this a little more realistic by going back into our database file then make our data fetching functions async to make it even more realistic I'll bring in this delay function from Dino to Prov a 1second delay to simulate latency in the database then from there I'll go back into the product page and make this server component async and add a weight to our function calls and now if we go back into the browser you'll notice that it renders but we also get this error what this error is telling us is that we need to make a choice we either need to cach or pre-render this page or we need to make it Dynamic explicitly by wrapping it in a suspense boundary let's first assume that we want this page to be dynamic and refetch the data on every request to clear the error the first thing need to do is wrap it in suspense and we can do that easily in nextjs by simply creating a loading file that exports a component this is basically the equivalent of using suspense in the parent layout but now if we go back to the application you'll notice that the error is cleared and we get fresh data on every request but now let's assume that we don't want Dynamic data and would rather cach our data well we can easily accomplish that by simply adding the used cache directive to the top of this page use cache is a nextjs specific feature and not directly related to reactjs s but what you'll notice is that when we go to the browser
Watch from 3:02now we get fresh data on the first render but then get that same data every time we refresh the page and that will continue until the cach expires and that's a good question when does the cach expire well currently the default is an infinite cache that's revalidated every 15 minutes which you'd want for a Content that doesn't change on a regular basis like your about page but what if we want to change the caching Behavior well there's a new cach life function that we can import from nextjs which we can then use in inside the body of the function to change the caching Behavior to a variety of different defaults like in this case we might only want to cach it for a few hours if the product description or price has the potential to change on a daily basis and if these defaults aren't good enough for you you can fully customize them to your own values in the next config but if that's still not good enough for you you can also invalidate the cash on demand which is made possible with this cash tag function you provide the function with a key that's used to identify a cached value and that means that at some point maybe in a couple minutes or a couple years you can invalidate the cache when the underlying data changes like typically that would happen when you update a record in the database that would impact what's presented to the user in the UI pretty cool although at this point we've only looked at ways to Cache an individual route but this Ed cache directive provides us with far more flexibility than that but for example we might have multiple components in a single file and if we put Ed cache at the top of that file all the components will inherit the same behavior if that's not desired though we can move the directive inside of individual components to choose exactly
Watch from 4:32which ones we want to opt in the most powerful feature though is its ability to Cache individual functions and server actions if we go back into the db. TS file we can actually Implement different caching behavior for each function maybe our product description is static and almost never changes is so let's put the use cache directive there in contrast the price might be highly Dynamic so let's leave that one as is now let's go back to our component and figure out how to use multiple levels of caching on a single page first make sure to remove the used cache directive from the top then we'll extract the price UI and data fetching logic into its own component this component will fetch and render the price in the UI just like before but the key difference is that we wrap that component in suspense in the parent what this will do is allow the rest of the page to render immediately while only the price remains suspended in a loading State and that's awesome because otherwise we would have to wait for the price before rendering anything on the page but now as you can see in the demo the user gets most of the content like the product description while the price finishes rendering in the background and that's especially powerful on things like dashboards where you're loading multiple different data sources all of which have different degrees of latency congratulations now that you understand use cach and suspense that's everything you'll need to memorize for caching in next1 15 it's usually a good thing when an API decreases in complexity but as of today Dynamic IO is still experimental and caching is still hard but I think this is a step in the right direction however in a big project this code mik it kind of crazy like your codebase will have used client use server and now use cache everywhere then you might
Watch from 6:03implement the new using keyword in JavaScript to use the new react use hook then combine them all to create your own use using directives and hooks at which point your code will be utterly useless but one other cool thing about next 15 is that it now also supports react 19 and the compiler the react compiler which eliminates the need for annoying hooks like use memo and use callback it's another step in the right direction but is still very experimental today but most importantly these featur are designed to provide job security by giving react developers a never-ending supply of Legacy code to update if react 19 ever comes out someday expect a full course on fireship iio and when that day comes you'll already have access to it if you're a lifetime member thanks for watching and I will see you in the next one
Watch from 7:34Full transcript
- 0:00
there are only two hard problems in computer science naming things cash invalidation and off by one errors maybe you've heard that joke before because another problem with programming is that we only have one joke and it's not very funny but there is some truth in the original joke and that's the fact that caching can be extremely difficult and the nextjs JavaScript framework is the poster child for these modern challenges
- 0:21
a few weeks ago forcell released nextjs 15 and it comes with all kinds of awesome new features like tools to automatically migrate code a fast turbo pack Dev server and a new API to run code in the background after a request is complete but the biggest change is that they totally overhaul the way caching works and to be honest it's pretty awesome and that's what we'll look at in this video by default
- 0:42
everything is cached in xjs like a server component that defines a web page and also any calls you make to the fetch function would be cached by default to try to optimize performance by preventing the server from doing extra work and rendering the same page over and over again the problem is that in some cases you might have multiple data fetching operations to render a page you might want some of them to be cashed but
- 1:03
you might want others to be revalidated on every request and opting out of the cash could be pretty annoying there's a few different ways to do it like adding the Cache no store option to fetch or by exporting this Force Dynamic variable or by setting the cach control headers manually it's kind of a mess and easy to run into problems where your data is not updating because it's being cached and you have no idea why the good news is
- 1:24
that in X15 things are becoming far more intuitive with a new API called Dynamic IO which allows you to cash or not cash anything while also simplifying your code and making it far more explicit to demonstrate how this works let's look at some code I'm here in a brand new nextjs project but currently this feature is experimental so let's enable it by adding Dynamic IO to the next config and
- 1:45
as of today we'll also need to be on the nextjs canary version which you can update to with these commands and optionally you'll notice that I'm using Dino here instead of nodejs because they have some cool utilities that we'll look at later but that's totally optional if you want to learn more about you know my full course is now available and I also just updated my nextjs course and if you're watching this before December 1st
- 2:05
2024 you can use the Black Friday discount to get access to everything at 40% off but now let's take a look at the new caching system in nextjs let's imagine we have an application that needs to display a product description and price to simulate that I've created this utility here that has a separate function for get product and get price I'm using the library Faker JS to
- 2:26
generate some fake data which you can think of as data you would fetch from a database interesting backstory on Faker JS a few years ago the original developer intentionally corrupted this project to break a bunch of people's apps on purpose as a statement against open source abuse and lack of funding it actually made it into the mainstream news and was the story that motivated me to start the code report series on the main Channel ultimately it didn't work
- 2:47
out too well for him and they took over the project and now it's maintained by someone else in this demo Faker JS is really useful because it makes it easy to tell which data is cached and which is not now from there I'm creating a page on the store Route inside of which we have a server component inside that component we get the product and price synchronously and then render it in the HTML if we go ahead and serve the
- 3:07
application you'll notice in the browser that every time I refresh the page I'm getting a new product price in description that's because currently this page is not cach and nextjs will render every time we refresh but now let's make this a little more realistic by going back into our database file then make our data fetching functions async to make it even more realistic I'll bring in this delay function from
- 3:28
Dino to Prov a 1second delay to simulate latency in the database then from there I'll go back into the product page and make this server component async and add a weight to our function calls and now if we go back into the browser you'll notice that it renders but we also get this error what this error is telling us is that we need to make a choice we either need to cach or pre-render this
- 3:48
page or we need to make it Dynamic explicitly by wrapping it in a suspense boundary let's first assume that we want this page to be dynamic and refetch the data on every request to clear the error the first thing need to do is wrap it in suspense and we can do that easily in nextjs by simply creating a loading file that exports a component this is basically the equivalent of using
- 4:08
suspense in the parent layout but now if we go back to the application you'll notice that the error is cleared and we get fresh data on every request but now let's assume that we don't want Dynamic data and would rather cach our data well we can easily accomplish that by simply adding the used cache directive to the top of this page use cache is a nextjs specific feature and not directly related to reactjs s but what you'll
- 4:30
notice is that when we go to the browser now we get fresh data on the first render but then get that same data every time we refresh the page and that will continue until the cach expires and that's a good question when does the cach expire well currently the default is an infinite cache that's revalidated every 15 minutes which you'd want for a Content that doesn't change on a regular basis like your about page but what if
- 4:52
we want to change the caching Behavior well there's a new cach life function that we can import from nextjs which we can then use in inside the body of the function to change the caching Behavior to a variety of different defaults like in this case we might only want to cach it for a few hours if the product description or price has the potential to change on a daily basis and if these defaults aren't good enough for you you
- 5:13
can fully customize them to your own values in the next config but if that's still not good enough for you you can also invalidate the cash on demand which is made possible with this cash tag function you provide the function with a key that's used to identify a cached value and that means that at some point maybe in a couple minutes or a couple years you can invalidate the cache when
- 5:34
the underlying data changes like typically that would happen when you update a record in the database that would impact what's presented to the user in the UI pretty cool although at this point we've only looked at ways to Cache an individual route but this Ed cache directive provides us with far more flexibility than that but for example we might have multiple components in a single file and if we put Ed cache at the top of that file all
- 5:56
the components will inherit the same behavior if that's not desired though we can move the directive inside of individual components to choose exactly which ones we want to opt in the most powerful feature though is its ability to Cache individual functions and server actions if we go back into the db. TS file we can actually Implement different caching behavior for each function maybe
- 6:16
our product description is static and almost never changes is so let's put the use cache directive there in contrast the price might be highly Dynamic so let's leave that one as is now let's go back to our component and figure out how to use multiple levels of caching on a single page first make sure to remove the used cache directive from the top then we'll extract the price UI and data
- 6:36
fetching logic into its own component this component will fetch and render the price in the UI just like before but the key difference is that we wrap that component in suspense in the parent what this will do is allow the rest of the page to render immediately while only the price remains suspended in a loading State and that's awesome because otherwise we would have to wait for the price before rendering anything on the
- 6:57
page but now as you can see in the demo the user gets most of the content like the product description while the price finishes rendering in the background and that's especially powerful on things like dashboards where you're loading multiple different data sources all of which have different degrees of latency congratulations now that you understand use cach and suspense that's everything you'll need to memorize for caching in
- 7:18
next1 15 it's usually a good thing when an API decreases in complexity but as of today Dynamic IO is still experimental and caching is still hard but I think this is a step in the right direction however in a big project this code mik it kind of crazy like your codebase will have used client use server and now use cache everywhere then you might implement the new using keyword in JavaScript to use the new react use hook
- 7:38
then combine them all to create your own use using directives and hooks at which point your code will be utterly useless but one other cool thing about next 15 is that it now also supports react 19 and the compiler the react compiler which eliminates the need for annoying hooks like use memo and use callback it's another step in the right direction but is still very experimental today but most importantly these featur are
- 7:59
designed to provide job security by giving react developers a never-ending supply of Legacy code to update if react 19 ever comes out someday expect a full course on fireship iio and when that day comes you'll already have access to it if you're a lifetime member thanks for watching and I will see you in the next one
Description
Upgrade to Fireship PRO https://fireship.io/pro
SponsorUse code BLACKFIRE for 40% off
Next.js 15 was released recently, with awesome new features like the React 19 compiler, background code, and the "use cache" directive. Learn about the new dynamicIO caching feature in Next.js
Next 15 Blog Post https://nextjs.org/blog/next-15
More from Beyond Fireship
×6.45:04Subtle, yet Beautiful Scroll Animations
Beyond Fireship2M views
×2.98:33Most overpowered way to build mobile apps?
Beyond Fireship925K views
×2.88:23This UI component library is mind-blowing
Beyond Fireship878K views
×2.76:17Industrial-scale Web Scraping with AI & Proxy Networks
Beyond Fireship854K views
