useTransition Performance Optimization Hook in React
The useTransition performance optimization hook allows us to update states without blocking the GUI.
With this hook we can set the update of some state to low priority, which will allow the update of other states to have high priority and be performed without delays.
An example would be filtering a drop-down list of products when the user enters characters into the search field. Of course, the list itself may be displayed with some delay, but we would not want the characters to be entered into the search field with a delay.
Let's see how the useTransition hook can help us in such cases. Let's assume we have a piece of code from the main component. Let's analyze it:
import { useTransition } from 'react';
import { useState } from 'react';
function App() {
const [isPending, startTransition] = useTransition();
const [filterTerm, setFilterTerm] = useState('');
const filteredProducts = filterProducts(filterTerm);
function updateFilterHandler(event) {
startTransition(() => {
setFilterTerm(event.target.value);
});
}
return (
<div>
<input type="text" onChange={updateFilterHandler} />
<ProductList products={filteredProducts} />
</div>
);
}
Here we see two variables for useTransition. The variable isPending contains a boolean value and shows whether the update process is finished, and startTransition is a function that allows us to lower the update priority:
const [isPending, startTransition] = useTransition();
We also have a state filterTerm, which stores the expression entered into the input field and a function setFilterTerm to set it:
const [filterTerm, setFilterTerm] = useState('');
Every time we type characters into the input, we have the updateFilterHandler function called, which updates filterTerm. This is where we implement our useTransition hook, wrapping the setFilterTerm setting function in startTransition like this:
function updateFilterHandler(event) {
startTransition(() => {
setFilterTerm(event.target.value);
});
}
This way we set the filterTerm state update to low priority and our input field will remain responsive.
Using the isPending variable, we can show the user that the list is still being updated. We'll display this information below the input field while the list is being updated:
return (
<div>
<input type="text" onChange={updateFilterHandler} />
{isPending && <p>updating ...</p>}
<ProductList products={filteredProducts} />
</div>
);