What is startTransition
React 18
React 18 concurrent mode has a new feature, namely startTransition
, which can prevent UI rendering from executing right away. startTransition
is needed because it can provide convenience in rendering the required UI immediately.
For example, when we want to use the search feature, we want to see the UI change immediately. So startTransition
can be used well to render the UI, such as viewing search results as we type.
Actually, you may not use startTransition
, you can use debounce or throttling, but this will be a problem if your application uses responsive features. startTransition
will make your React app noticeably faster, and can reduce the burden of rendering items in your app that you don’t really need.
I will give you an example of how to use startTransition
below.
React 18 version example, make sure your package.json is like this:
"react": "^18.2.0",
"react-dom": "^18.2.0",
The src/index.js
file from React 18 already supports concurrent mode.
const root = ReactDOM.createRoot(document.getElementById('root'));root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Now I will show you how to use startTransition
in src/App.js
import React, { useState, useTransition } from 'react';
import './App.css';const App = () => {
const [isPending, startTransition] = useTransition();
const [searchResult, setSearchResult] = useState(); const handleChange = (e) => {
startTransition(() => {
setSearchResult(e.target.value);
});
};return (
<div className="App">
<header className="App-header">
<div className="SearchEngine">
<div className="SearchInput">
<input type="text" onChange={handleChange} />
</div>
{isPending ? (
<div>
<span>Loading...</span>
</div>
) : (
<div>
<span>{searchResult}</span>
</div>
)}
</div>
</header>
</div>
);
}export default App;
This code above will show loading
indicator instead searchResult
when you type faster, which means loading
the indicator is displayed first.
Use startTransition
will make your React App run smoothly and reactive, because startTransition
will separate which UI needs to render immediately and where is non-urgent UI that can be delayed to display. isPending
will indicate the status of the transition.
Thank you