JAVASCRIPT

Improve Responsiveness with `useTransition` for Non-Urgent React Updates

Leverage React 18's `useTransition` hook to mark state updates as non-urgent, keeping the UI responsive during long-running data-intensive operations.

import React, { useState, useTransition } from 'react';

const generateExpensiveData = (size) => {
  const data = [];
  for (let i = 0; i < size; i++) {
    data.push(`Item ${i + 1} - ${Math.random().toFixed(4)}`);
  }
  return data;
};

function TransitionComponent() {
  const [isPending, startTransition] = useTransition();
  const [inputValue, setInputValue] = useState('');
  const [displayData, setDisplayData] = useState([]);

  const handleInputChange = (e) => {
    setInputValue(e.target.value); // Urgent update: input value

    // Non-urgent update: expensive data generation
    startTransition(() => {
      setDisplayData(generateExpensiveData(parseInt(e.target.value || '0', 10)));
    });
  };

  return (
    <div>
      <input
        type="number"
        placeholder="Enter count for data items"
        value={inputValue}
        onChange={handleInputChange}
        style={{ width: '200px', padding: '8px' }}
      />
      {isPending && <p>Loading data...</p>}
      <div style={{ marginTop: '20px', maxHeight: '300px', overflowY: 'auto', border: '1px solid #ccc' }}>
        {displayData.map((item, index) => (
          <p key={index}>{item}</p>
        ))}
      </div>
    </div>
  );
}
How it works: The `useTransition` hook, introduced in React 18, allows you to mark certain state updates as 'transitions' or non-urgent. This tells React that these updates can be interrupted by more urgent updates (like typing in an input field), preventing the UI from freezing during heavy computations. `startTransition` wraps the expensive state update, and `isPending` provides a way to show a loading indicator while the transition is in progress, improving the perceived responsiveness of the application.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs