ReactJS - startTransition()



StartTransition is a React function that allows developers to update the application's state without interrupting the user interface. In other words, it allows us to do state updates while keeping our web app from becoming slow or unresponsive.

The startTransition function is used to mark a state update as a "transition." It is very helpful when we need to make multiple state updates at the same time. React ensures that these updates are non-blocking by identifying them as transitions, which means they will not produce unwanted loading indicators or make our app feel slow.

Syntax

startTransition(scope)

Parameters

scope − It is a function that calls one or more set functions to update some state. React directly calls scope with no parameters, and all synchronous state updates scheduled during the scope function call are marked as transitions. They will not block traffic and will not display unwanted loading signals.

Return Value

This function does not return anything.

Examples

Example − Basic Example

In this example app we will have a simple counter that increments when the button is clicked. The startTransition function is used to make the update smoother. So the code for this app is as follows −

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

function BasicApp() {
   const [count, setCount] = useState(0);   
   const handleClick = () => {
      startTransition(() => {
         setCount(count + 1);
      });
   };
   
   return (
      <div>
         <p>Count: {count}</p>
         <button onClick={handleClick}>Increment</button>
      </div>
   );
}

export default BasicApp;

Output

count increment

Example − List Rendering

In this example we use the startTransition function when adding items to a list to ensure a smooth user experience. So we will also have a button to add items in the list by clicking that item the new item will be added to the list. So the code for this app is as follows −

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

function ListApp() {
   const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3']);   
   const handleAddItem = () => {
      startTransition(() => {
         setItems([...items, `Item ${items.length + 1}`]);
      });
   };
   
   return (
      <div>
         <ul>
            {items.map((item, index) => (
            <li key={index}>{item}</li>
            ))}
         </ul>
         <button onClick={handleAddItem}>Add Item</button>
      </div>
   );
}

export default ListApp;

Output

reactapp_add_item.jpg

Example − Switch between Tabs

To use startTransition we need to follow certain steps −

  • First we will have to import React's startTransition method in our code.

  • Now with the help of useState, we can define the state we want to update within our component or method.

  • Now we can write a function that does the state update, then wrap it in a startTransition call.

  • So when we call startTransition, React is directed to treat the state update as a transition, which makes it non-blocking.

The app includes

Step 1 − We will import useState and startTransition methods.

Step 2 − We will define the currentTab state variable within the TabSwitcher component, which keeps track of the currently selected tab.

Step 3 − We will define the switchTab function, which takes a tab name as an input. To update the currentTab state, this function calls startTransition. We ensure that the tab switching is non-blocking and does not cause the UI to become unresponsive by enclosing this state update in startTransition.

Step 4 − The render method shows two tabs and their associated content. When we click a tab button, the switchTab function is called, which refreshes the selected tab in a non-blocking way.

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

function App() {
   const [currentTab, setCurrentTab] = useState('Tab 1');   
   const switchTab = (tabName) => {
      startTransition(() => {
         setCurrentTab(tabName);
      });
   };
   
   return (
      <div>
         <h1>Tab Switcher</h1>
         <div className="tabs">
            <button
               className={currentTab === 'Tab 1' ? 'active-tab' : 'tab'}
               onClick={() => switchTab('Tab 1')}
            >
               Tab 1
            </button>
            <button
               className={currentTab === 'Tab 2' ? 'active-tab' : 'tab'}
               onClick={() => switchTab('Tab 2')}
            >
               Tab 2
            </button>
         </div>
         <div className="tab-content">
            {currentTab === 'Tab 1' && <p>This is the content of Tab 1.</p>}
            {currentTab === 'Tab 2' && <p>This is the content of Tab 2.</p>}
         </div>
      </div>
   );
}

export default App;

Output

tab switcher

Limitations

  • startTransition doesn't help track pending transitions. To show a loading indicator during a transition, use useTransition.

  • We can use startTransition only if we have access to the state's set function.

  • The function given to startTransition should be synchronous. It runs immediately, marking state updates during its execution as transitions.

  • A state update marked as a transition can be interrupted by other updates.

Summary

By providing non-blocking state updates, React's startTransition method assists us for creating highly responsive UIs. We make sure our application remains responsive even during re-renders by choosing particular state changes as transitions.

reactjs_reference_api.htm
Advertisements