perf(next): reduce getNavPrefs calls from 3 to 1 per page load (#11318)
Previously, we were calling `getNavPrefs` (a payload.find call) three times for every single page load. This PR: 1. Ensures that `getNavPrefs` is called only once per page load, reducing two unnecessary `payload.find` calls every time a page is loaded or navigated to. 2. Adds `pagination: false` to the `payload.find` call, making it more efficient and improving performance. ## How? We were using React's cache to ensure that navigation preferences (`getNavPrefs`) were fetched only once per request. However, this wasn't working as expected because the first argument of `getNavPrefs` was an object. Each time it was called, a new object reference was passed, preventing React from caching it properly. To fix this, this PR ensures that only primitive values are used as arguments for caching, following best practices and making the cache function work as intended.
This commit is contained in:
@@ -1,16 +1,20 @@
|
||||
import type { NavPreferences, Payload, User } from 'payload'
|
||||
import type { DefaultDocumentIDType, NavPreferences, Payload, User } from 'payload'
|
||||
|
||||
import { cache } from 'react'
|
||||
|
||||
export const getNavPrefs = cache(
|
||||
async ({ payload, user }: { payload: Payload; user: User }): Promise<NavPreferences> =>
|
||||
user
|
||||
async (
|
||||
payload: Payload,
|
||||
userID: DefaultDocumentIDType,
|
||||
userSlug: string,
|
||||
): Promise<NavPreferences> => {
|
||||
return userSlug
|
||||
? await payload
|
||||
.find({
|
||||
collection: 'payload-preferences',
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
user,
|
||||
pagination: false,
|
||||
where: {
|
||||
and: [
|
||||
{
|
||||
@@ -20,17 +24,18 @@ export const getNavPrefs = cache(
|
||||
},
|
||||
{
|
||||
'user.relationTo': {
|
||||
equals: user.collection,
|
||||
equals: userSlug,
|
||||
},
|
||||
},
|
||||
{
|
||||
'user.value': {
|
||||
equals: user.id,
|
||||
equals: userID,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
?.then((res) => res?.docs?.[0]?.value)
|
||||
: null,
|
||||
: null
|
||||
},
|
||||
)
|
||||
|
||||
@@ -68,7 +68,7 @@ export const DefaultNav: React.FC<NavProps> = async (props) => {
|
||||
i18n,
|
||||
)
|
||||
|
||||
const navPreferences = await getNavPrefs({ payload, user })
|
||||
const navPreferences = await getNavPrefs(payload, user?.id, user?.collection)
|
||||
|
||||
const LogoutComponent = RenderServerComponent({
|
||||
clientProps: {
|
||||
|
||||
@@ -82,7 +82,7 @@ export const RootLayout = async ({
|
||||
})
|
||||
}
|
||||
|
||||
const navPrefs = await getNavPrefs({ payload, user: req.user })
|
||||
const navPrefs = await getNavPrefs(req.payload, req.user?.id, req.user?.collection)
|
||||
|
||||
const clientConfig = getClientConfig({
|
||||
config,
|
||||
|
||||
Reference in New Issue
Block a user