Blog>
Snippets

Using the New Concurrent Mode

Showcase how to enable and utilize the concurrent mode in React for better performance and user experience by handling state updates and transitions.
import { createRoot } from 'react-dom/client';
import App from './App';  // Import the App component from App.js

// Assuming there is a div with id 'root' in your index.html
const container = document.getElementById('root');
// Create a root.
const root = createRoot(container);

// Initial render: Render an element to the root.
root.render(<App tab="home" />);
This code snippet demonstrates how to initiate a Concurrent Mode in React by using 'createRoot' instead of 'ReactDOM.render'. The 'createRoot' function is used to create a root for the React application, and the 'render' method of this root is then used to render the 'App' component. This setup enables Concurrent Mode features.
import React, { Suspense, useState, startTransition } from 'react';

function MyComponent() {
  const [inputValue, setInputValue] = useState('');
  // Wrap state updates you want to be interruptible in startTransition
  const handleInputChange = (e) => {
    startTransition(() => {
      setInputValue(e.target.value);
    });
  };

  return (
    <div>
      <input type="text" value={inputValue} onChange={handleInputChange} />
      <Suspense fallback={<div>Loading...</div>}>
        {/* Dynamically loaded component with the input value */}
        <ExpensiveComponent inputValue={inputValue} />
      </Suspense>
    </div>
  );
}

// Some expensive component that takes prop 'inputValue'
function ExpensiveComponent({ inputValue }) {
  // Component implementation here that might be intensive to render
  return <div>Displaying data based on: {inputValue}</div>;
}

export default MyComponent;
In this example, 'MyComponent' utilizes Concurrent Mode to manage an input's state. React's startTransition is used when setting the state derived from the input's onChange event. This defers the state update without blocking user input. The 'ExpensiveComponent' is an example of a component that could potentially be resource-intensive to render, and is wrapped in 'Suspense' to specify a fallback UI while it's loading or rendering.
/* Add in index.css */
input {
  transition: color 0.2s ease-in-out;
}

input.updating {
  color: #999;  /* Grey out input text during transitions */
}
This CSS code styles the input field and defines a transition for text color change. It includes an additional 'updating' class that can be applied to the input field to visually indicate when the data is in a transition phase (state updates are deferred).