Discover the Power of Next.js 13+
The latest version of Next.js introduces an experimental app folder that addresses specific use cases with precision.
Easily Share Values Between Components Using React Context
- Retrieve data in a React Server Component (RSC) layout
- Create a React context within this layout and pass the value to it
- Access and utilize this context across your application as needed
You can also configure this context in a nested RSC, allowing for more granular control over where the value is available.
In a real-life scenario example, a survey definition fetched in a page RSC is passed down to client code via context provided by a typed reusable hook offered by context provider.
Snippet for the React Server Component (page):
// /app/referer/page.tsx (Server Component)
import { headers } from 'next/headers'
export default async function Page() {
const headersList = headers()
const referer = headersList.get('referer')
return (
<RefererProvider value={referer}>
<InteractiveReferer />
</RefererProvider>
)
}
Example code for the client context (ensure to include the "use client"
directive):
// /components/InteractiveReferer.tsx (Client Component)
// use "client"
export const InteractiveReferer = () => {
const referer = useRefererContext()
const [clickedReferer, setClickedReferer] = useState(false)
return (
<button
onClick={() => {
setClickedReferer(true)
}}
>
Referer: {referer}
</button>
)
}
Effortlessly Pass Data between RSCs through Caching
An intriguing feature of the enhanced Next.js app structure is the ability to utilize server-side code beyond the traditional getServerSideProps
at the page level. Nested components can now be Server Components that trigger server requests. To establish not only a client-side context but also a server-side context scoped to the ongoing request may prove beneficial.
Detailed insights into this approach are covered in this informative article. By leveraging the not-yet-documented React 18 cache
function, you can accomplish such contextual scoping. A practical demonstration showcasing this concept can be found here.
import { cache } from "react";
export const getServerContext = cache(() => ({
// dummy context for illustration
createdAt: Date.now().toString(),
calledByLayout: false,
calledByPage: false,
calledByNested: false
}))
You have the flexibility to modify the returned value directly to incorporate new information into this contextual cache.
Note: The term "server context" is used here to denote data stored in cache
serving as a context. As a counterpart to the "client" context, this terminology aligns well. However, in future updates of Next.js and React, "Request cache" might emerge as a more fitting description for this purpose of sharing data between RSCs and client components.
Smart Handling of Data with Get/Set Functions and Layouts
Within RSCs, the utilization of the "cache" function facilitates the implementation of "cached getters," ensuring efficient retrieval of data without overwhelming API calls or database queries. In scenarios where deriving values from page props and passing them to children sans prop drilling is necessary, consider exploring alternative patterns like those offered by the server-only-context package.
While establishing a value in a layout and accessing it from a page isn't always a straightforward process due to client-side navigation dynamics, embracing these innovative approaches can streamline complex data management requirements effectively.