Skip to content

Commit 2bd098c

Browse files
authored
perf(ui): prevent unnecessary client config sanitization (#12665)
- The `ConfigProvider` was unnecessarily sanitizing the client config twice on initial render, leading to an unnecessary re-render. Now it only happens once - Memoizes the context value to prevent accidental, unnecessary re-renders of consumers
1 parent 08ec837 commit 2bd098c

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

packages/ui/src/providers/Config/index.tsx

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import type {
99
UnsanitizedClientConfig,
1010
} from 'payload'
1111

12-
import React, { createContext, use, useCallback, useEffect, useMemo, useState } from 'react'
12+
import React, { createContext, use, useCallback, useEffect, useMemo, useRef, useState } from 'react'
1313

1414
type GetEntityConfigFn = {
1515
// Overload #1: collectionSlug only
@@ -64,9 +64,15 @@ export const ConfigProvider: React.FC<{
6464
}> = ({ children, config: configFromProps }) => {
6565
const [config, setConfig] = useState<ClientConfig>(() => sanitizeClientConfig(configFromProps))
6666

67+
const isFirstRenderRef = useRef(true)
68+
6769
// Need to update local config state if config from props changes, for HMR.
6870
// That way, config changes will be updated in the UI immediately without needing a refresh.
6971
useEffect(() => {
72+
if (isFirstRenderRef.current) {
73+
isFirstRenderRef.current = false
74+
return
75+
}
7076
setConfig(sanitizeClientConfig(configFromProps))
7177
}, [configFromProps])
7278

@@ -98,9 +104,9 @@ export const ConfigProvider: React.FC<{
98104
[collectionsBySlug, globalsBySlug],
99105
)
100106

101-
return (
102-
<RootConfigContext value={{ config, getEntityConfig, setConfig }}>{children}</RootConfigContext>
103-
)
107+
const value = useMemo(() => ({ config, getEntityConfig, setConfig }), [config, getEntityConfig])
108+
109+
return <RootConfigContext value={value}>{children}</RootConfigContext>
104110
}
105111

106112
export const useConfig = (): ClientConfigContext => use(RootConfigContext)

0 commit comments

Comments
 (0)