Introduction
This post will give a simple application that can leverage the useTransition and startTransition feature in react.js version 18 and higher.
Transitions
The transitions are the one that are executed to indicate a change in state from one to the other. For example, in a user listing component, we might have a transition to happen whenever the user tries to filter / sort the data from the grid.
React.js has enabled these to be tracked because it involves mostly a user activity to transition from one state to the another state.
Why does react.js want to capture or perform these transitions?
The main reason for this is to optimize the rendering of the DOM which is a complex and time consuming process.
Example
Let us consider a scenario where the developer builds a react.js application (like the one in my sample code) which filters a grid of user's from the input captured through a text box.
Note:
This sample is not following the best practice because in real-time apps, we will use debouncing to prevent bombarding the API for each keypress happening in the UI to start the filtering of the data.
In this case, when the user tries to filter, even with debouncing in place, there might be situations where the user is typing slowly or more number of characters or clears and starts a new search etc.
This typically does not apply to search, it can be applied to grid sorting, widget movements in a dashboard, column re-ordering or row data reordering etc.
To sum-up, this can be applied to any type of operation that involves potentially many temporary steps before reaching the final state and each of these temporary state changes might involve a API call or a costlier DOM manipulation operation.
In order to avoid frequent DOM manipulation (as per our above examples), react uses a transition which identifies the operations and defers them or cancels the intermediate ones so that the costlier operations are minimized.
Let us say for example in a page, if there are many DOM manipulations happening like widget drag drop, content rendering, etc., React will prefer to skip few of the intermediate drag-n-drop transitions and use the final one alone to render so that the page will be rendered faster than frequent rendering. In the mean time, React starts to perform the rendering of the content which does not have any transitions.
Hope these examples clarify the details on transitions.
Sample Code
The below given code is for a temporary transition indicator or spinner / loader for indicating to the user that there is a transition in place in the UI (DOM). We have a background color as "red" to see a visible change in the UI
const Spinner = (props) => {
return <div style={{ backgroundColor: "red" }}>Loading ...</div>;
};
export default Spinner;
The below code shows a sample component that uses an in-place collection of users that gets rendered in a table. There is a text box that the user can type in to filter the data by either the first or the last name of the user.
import React, { useState, useTransition } from "react";
import Spinner from "./Spinner";
import "./UserListing.css";
const UserListing = (props) => {
const userDetails = [
{
id: 1,
first: "Mark",
last: "Otto",
handle: "@m_otto"
},
{
id: 2,
first: "Elon",
last: "Musk",
handle: "@m_elon"
},
{
id: 3,
first: "John",
last: "Smith",
handle: "@s_john"
}
];
const [users, setUsers] = useState(userDetails);
const [isUserFilterPending, startTransition] = useTransition();
const filterUsers = (e) => {
startTransition(() => {
console.log("running transition");
setUsers(
userDetails.filter(
(x) =>
x.first.toLowerCase().startsWith(e.target.value) ||
x.last.toLowerCase().startsWith(e.target.value)
)
);
});
};
return (
<>
<h1>Users in Contoso Inc., </h1>
<div>
<input
type="text"
placeholder="Enter a name to filter"
onChange={filterUsers}
/>
</div>
{isUserFilterPending && <Spinner />}
<div>
<table className="table">
<thead>
<tr>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
{users.map((user) => {
return (
<tr key={user.id}>
<td>{user.first}</td>
<td>{user.last}</td>
<td>{user.handle}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</>
);
};
export default UserListing;
Once this code is run in the browser, you can visualize the transition indication when the user tries to filter or clear the filter happening in the UI.
To see a live demo on how this works, please click this link
Comments
Post a Comment