Зміст курсу
Next.js 14
Next.js 14
Loaders
Previously, we covered making the app dynamic. However, dealing with a large amount of data may result in slow data fetches, negatively impacting the application's performance.
Now, let's delve into strategies for improving the user experience when handling sluggish data requests.
Theory
We can use the widely used technique called Streaming.
Streaming is a way of sending information in smaller parts instead of all at once. Imagine it like breaking down a long journey into smaller steps and only taking each step when you're ready. This helps avoid delays and lets you see and use parts of a webpage without waiting for everything to load.
In Next.js, there are two ways to do streaming:
- For the whole webpage, we use a file called
loading.tsx
; - For specific parts of the webpage, we use something called
<Suspense>
.
Let's take a closer look at how this works.
Streaming the entire page
Let's create a loading.tsx
file in the dashboard
folder to add a loader to the entire dashboard page.
loading.tsx
: This is a special file in Next.js that usesSuspense
. It helps us create a temporary UI (fallback UI) to display while the page's main content is loading;- Since the
<Sidebar>
is static (doesn't change), it appears immediately. Users can interact with it even while the dynamic content is loading.
Great job! You've just used streaming.
Fixing bug
The current issue we are encountering is the loader utilized in the loading.tsx
file is applied to all pages within the dashboard
folder. However, what if we need specific UI elements for each app page?
To address this bug, we can implement Route Groups. Create an (overview)
folder inside the dashboard
directory and relocate the loading.tsx
and page.tsx
files there.
By doing this, the loading.tsx
file will exclusively apply to the dashboard page, resolving the issue.
Route Groups help us neatly organize files without changing the web address. When we make a folder with parentheses ()
, the folder name won't be part of the web address. For instance, /dashboard/(overview)/page.tsx
becomes just /dashboard
.
Дякуємо за ваш відгук!