![]() |
VOOZH | about |
When building interactive user interfaces, performance is a crucial aspect to consider. One way to improve the performance of a React application is by using the useTransition hook. This hook allows you to specify some state updates as not as important, by separating the animation-related state changes from the other state changes in your component.
In this article, we will explore the basics of the useTransition hook and how it can be used to improve the performance of a React application.
useTransition hook enables us to specify which state changes are critical or urgent and which are not.
All state changes are viewed as necessary in React. There may be certain quick UI updates, like selecting a value from a dropdown menu, that should take precedence over other updates, like list filtering, which might slow down their execution. A useTransition hook allows us to specify what state changes should run with a lower priority to increase the performance of our application.
Syntax:
const [isPending, startTransition] = useTransition()The useTransition hook does not take any parameters, and it returns two values:
Let's see few examples of how useTransition works in practice.
Creating React Application:
Step 1: Make a project directory, head over to the terminal, and create a react app named usetransition-example using the following command:
npx create-react-app usetransition-exampleStep 2: After the usetransition-example app is created, switch to the new folder usetransition-example by typing the command below:
cd usetransition-exampleProject Structure: We will modify the folder and keep the files we need for this example. Now, make sure your file structure looks like this:
Example 1: We will use the useTransition hook to change the visibility of a text and to change the text itself.
index.html: Include the following code in your index.html file, located in the public folder of your project directory.
App.js:
App.css: Add the following code to App.css to style the application.
index.js: Add the following code to the index.js file.
Step to run the application: Run the application by using the following command:
npm startOutput: By default, the React project will run on port 3000. You can access it at localhost:3000 on your browser.
Example 2: Updating list items using useTransition hook.
The startTransition will contain the setList method. This indicates that updating the state of setList is of low priority while updating the input field takes precedence. It ensures that we can still interact with our application even if our code runs slowly.
App.js:
Step to run the application: Run the application by using the following command:
npm startOutput:
The input field updates instantly as we type, while the list is rendered after it finishes loading.