Blog>
Snippets

Optimizing Performance with Error Boundary

Illustrate best practices for optimizing performance when using QueryErrorResetBoundary, such as preventing unnecessary component rerenders.
import { useState } from 'react';
import { QueryErrorResetBoundary } from 'react-query';
import { ErrorBoundary } from 'react-error-boundary';
import ErrorFallback from './ErrorFallback'; // Assume this is a custom component for error display

function MyComponent() {
  const [key, setKey] = useState(0); // Key for triggering re-renders

  return (
    <QueryErrorResetBoundary>
      {({ reset }) => (
        <ErrorBoundary
          FallbackComponent={ErrorFallback}
          onReset={() => {
            // Resetting the state to trigger a re-render
            setKey(prevKey => prevKey + 1);
            reset(); // Resetting queries
          }}
          resetKeys={[key]} // Listen to changes on `key` to reset boundary
        >
          {/* Your main component code here */}
        </ErrorBoundary>
      )}
    </QueryErrorResetBoundary>
  );
}
This example demonstrates how to use QueryErrorResetBoundary with ErrorBoundary to optimize performance by preventing unnecessary re-renders. A key is used to control the re-render of the component only when necessary, such as after an error is reset. This is done by updating the key, which is listened to by the ErrorBoundary's resetKeys prop.