Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize useSWRConfig hook with useMemo to maintain stable reference #4093

Open
samuel871211 opened this issue Feb 15, 2025 · 0 comments
Open

Comments

@samuel871211
Copy link
Contributor

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:

  1. The optimization implementation shown above
  2. Test cases to verify the stable reference behavior
  3. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant