Template
layout
Templates are similar to layouts in that they wrap each child layout or page. Unlike layouts that persist across routes and maintain state, templates create a new instance for each of their children on navigation. This means that when a user navigates between routes that share a template, a new instance of the component is mounted, DOM elements are recreated, state is not preserved, and effects are re-synchronized. There may be cases where you need those specific behaviors, and templates would be a more suitable option than layouts. For example: - Features that rely on useEffect (e.g logging page views) and useState (e.g a per-page feedback form). - To change the default framework behavior. For example, Suspense Boundaries inside layouts only show the fallback the first time the Layout is loaded and not when switching pages. For templates, the fallback is shown on each navigation.
Taint
security
A Client Component should never accept objects that carry sensitive data. Ideally, the data fetching functions should not expose data that the current user should not have access to. Sometimes mistakes happen during refactoring. To protect against these mistakes happening down the line we can βtaintβ the user object in our data API.
Server Only end Env
security
server-only: server-only packages prevent code running on the frontend. ENV: NEXT_PUBLIC prefix can be referred to by frontend.
Server Components
rendering
React Server Components allow you to write UI that can be rendered and optionally cached on the server. By default, Next.js uses Server Components.
Server and Client Composition Patterns
rendering
When building React applications, you will need to consider what parts of your application should be rendered on the server or the client.
Optimistic Updates
server-actions
useOptimistic is a React Hook that lets you show a different state while an async action is underway. It accepts some state as an argument and returns a copy of that state that can be different during the duration of an async action such as a network request. You provide a function that takes the current state and the input to the action, and returns the optimistic state to be used while the action is pending. This state is called the βoptimisticβ state because it is usually used to immediately present the user with the result of performing an action, even though the action actually takes time to complete.
Non-form Elements
server-actions
While it's common to use Server Actions within <form> elements, they can also be invoked from other parts of your code such as event handlers and useEffect.
Server Actions
server-actions
Server Actions are asynchronous functions that are executed on the server. They can be used in Server and Client Components to handle form submissions and data mutations in Next.js applications.
RSC Payload
rendering
The RSC Payload is a compact binary representation of the rendered React Server Components tree. It's used by React on the client to update the browser's DOM. The RSC Payload contains: - The rendered result of Server Components - Placeholders for where Client Components should be rendered and references to their JavaScript files - Any props passed from a Server Component to a Client Component
Router Cache (@client)
caching
Next.js has an in-memory client-side cache that stores the React Server Component Payload, split by individual route segments, for the duration of a user session. This is called the Router Cache. The cache is stored in the browser's temporary memory. Two factors determine how long the router cache lasts: - Session: The cache persists across navigation. However, it's cleared on page refresh. - Automatic Invalidation Period: The cache of an individual segment is automatically invalidated after a specific time. The duration depends on whether the route is statically or dynamically rendered: - Dynamically Rendered: 30 seconds - Statically Rendered: 5 minutes While a page refresh will clear all cached segments, the automatic invalidation period only affects the individual segment from the time it was last accessed or created.
Route Handlers
route-handlers
Route Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs. Route Handlers can be nested inside the app directory, similar to page.js and layout.js. But there cannot be a route.js file at the same route segment level as page.js.
Request Memoization (@server)
caching
React extends the fetch API to automatically memoize requests that have the same URL and options. This means you can call a fetch function for the same data in multiple places in a React component tree while only executing it once.
Conditional Routes
parallel-routes
Parallel Routes can be used to implement conditional routing. For example, you can render a @dashboard or @login route depending on the authentication state.
Parallel Routes
parallel-routes
Parallel Routing allows you to simultaneously or conditionally render one or more pages in the same layout. For highly dynamic sections of an app, such as dashboards and feeds on social sites, Parallel Routing can be used to implement complex routing patterns. Slots(@) are not route segments and do not affect the URL structure.
Overwriting Metadata
metadata
Next.js has a Metadata API that can be used to define your application metadata (e.g. meta and link tags inside your HTML head element) for improved SEO and web shareability.
Nesting Layouts
layout
A layout is UI that is shared between multiple pages. On navigation, layouts preserve state, remain interactive, and do not re-render. Layouts can also be nested.
Loading with Streaming
loading
In addition to loading.js, you can also manually create Suspense Boundaries for your own UI components. The App Router supports streaming with Suspense for both Node.js and Edge runtimes.
Loading with Preloading Data
loading
Another way to prevent waterfalls is to use the preload pattern. You can optionally create a preload function to further optimize parallel data fetching. With this approach, you don't have to pass promises down as props. The preload function can also have any name as it's a pattern, not an API.
Loading Immediately
loading
An instant loading state is fallback UI that is shown immediately upon navigation. You can pre-render loading indicators such as skeletons and spinners, or a small but meaningful part of future screens such as a cover photo, title, etc. This helps users understand the app is responding and provides a better user experience. Create a loading state by adding a loading.js file inside a folder.
Modal with Parallel Routes
intercepting-routes
Intercepting Routes can be used together with Parallel Routes to create modals. Using this pattern to create modals overcomes some common challenges when working with modals, by allowing you to: - Make the modal content shareable through a URL - Preserve context when the page is refreshed, instead of closing the modal - Close the modal on backwards navigation rather than going to the previous route - Reopen the modal on forwards navigation