Skip to content

Optimize useSWRConfig hook with useMemo to maintain stable reference #4093

@samuel871211

Description

@samuel871211

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions