Blog>
Snippets

Optimizing Performance with Concurrent Mode

Explain how to enable React's Concurrent Mode in a project and demonstrate its impact on performance when used together with Suspense and React Query for asynchronous data fetching.
import { createRoot } from 'react-dom/client';
import App from './App';

// Assuming you have an 'App' component
// Enable Concurrent Mode by using createRoot instead of ReactDOM.render
cost container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);
This code snippet enables Concurrent Mode in a React project by using 'createRoot' instead of 'ReactDOM.render'. It mounts the 'App' component to the 'root' DOM node in Concurrent Mode.
import React, { Suspense } from 'react';
import { useQuery } from 'react-query';

function FetchData() {
  const { isLoading, error, data } = useQuery('repoData', () =>
    fetch('https://api.github.com/repos/tannerlinsley/react-query').then(res =>
      res.json()
    )
  );

  if (isLoading) return 'Loading...';

  if (error) return 'An error has occurred: ' + error.message;

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.description}</p>
    </div>
  );
}

export default function App() {
  return (
    <Suspense fallback={<h1>Loading profile...</h1>}>
      <FetchData />
    </Suspense>
  );
}
This code snippet demonstrates how to fetch asynchronous data using React Query within a React component wrapped with Suspense for better loading handling and performance optimization. The 'Suspense' component displays a fallback UI until the data fetch is complete.