-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Optimize useSWRConfig hook with useMemo to maintain stable reference #4093
Description
Performance Optimization Suggestion
Description / Observed Behavior
export const useSWRConfig = (): FullConfiguration => {
return mergeObjects(defaultConfig, useContext(SWRConfigContext))
}The current implementation of useSWRConfig hook creates a new configuration object on every render by merging the default config with the context config. This causes unnecessary re-renders in components that depend on the config reference, even when the actual configuration values haven't changed.
Expected Behavior
export const useSWRConfig = (): FullConfiguration => {
const parentConfig = useContext(SWRConfigContext);
const mergedConfig = useMemo(
() => mergeObjects(defaultConfig, parentConfig),
[defaultConfig, parentConfig]
)
return mergedConfig;
}The useSWRConfig hook should maintain a stable reference to the merged configuration object across re-renders when the underlying configs (default and context) haven't changed. This would prevent unnecessary re-renders in dependent components.
Repro Steps / Code Example
const swrConfig: SWRConfiguration = {
revalidateOnMount: true,
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
function App() {
return (
<SWRConfig value={swrConfig}>
<ChildComponent/>
</SWRConfig>
)
}
function ChildComponent() {
const [counter, setCounter] = useState(0)
const swrConfig = useSWRConfig()
useEffect(() => {
// This effect runs on every render because config reference changes
console.log('Config changed')
}, [swrConfig ])
return (
<button onClick={() => setCounter(prev => prev + 1)}>
counter + 1
</button>
)
}Additional Context
SWR version: 2.3.2
I'd be happy to submit a PR with this fix if you think this is a valid issue. The PR would include:
- The optimization implementation shown above
- Test cases to verify the stable reference behavior
- Documentation updates if needed
Let me know if you'd like me to proceed with the PR or if you have any other suggestions for improvement.