useTransition
by Tomas Trescak· React Hooks

0 / 1820 XP

Presentation Transcript
If you prefer text to video, check out the transcript of the presentation above

Slide 1 ----------- Part 1: Let's explore how can we further optimise user experience when dealing with complex, long computations, using the useTransition hook. Slide 2 ----------- Part 1: With useTransition we can make React apps more responsive ... Part 2: ... since users expect smooth experiences, especially when handling large datasets or complex UI updates. Part 3: Without optimization, React updates can cause the UI to lag, especially during filtering or sorting operations. Part 4: The useTransition hook helps defer non-urgent updates while keeping urgent interactions instant. Let's take a look at an example. Slide 3 ----------- Part 1: When updating state inside an event handler, React blocks the UI until the update completes. Part 2: Imagine filtering a list of 10,000 products. Without optimization, each keystroke triggers a re-render. Part 3: The culprit is this filtering methods that has to filter thousands of records on each keystroke, freezing the UI until the filtering is complete. Slide 4 ----------- Part 1: Consider this example that uses over 5000000 records to filter in your app. Part 2: In our query handler, we filter the list with the current value of the filter query, leading to a very sluggish experience. Try typing your values in the search box. Let's fix that! Slide 5 ----------- Part 1: First, let's import the useTransition hook Part 2: Then, let's initiate the hook, obtaining the isPending flag and startTransition function Part 3: Then, we use the startTransition function providing a parameter which is a function in which we filter our long list. Part 4: Last, we can use the isLoading flag to show user that the system is filtering the records. Part 5: Typing in the query field will now yield in a much better user experience! Let's break it down. Slide 6 ----------- Part 1: With useTransition, we can prioritize fast updates while deferring slow ones. Part 2: React processes updates asynchronously, keeping interactions responsive. Part 3: useTransition gives us two values: isPending (indicates loading) and startTransition (wraps low-priority updates). Part 4: Any state updates inside startTransition are considered non-urgent and executed asynchonously. Part 5: isPending is a boolean value that tells us when a transition is happening—useful for showing loading indicators. Slide 7 ----------- Part 1: So, when should you use useTransition? Part 2: The Best Use Cases are: Filtering large lists, Sorting heavy datasets, or Rendering complex components Part 3: Do not use this hook when updates must be immediate, for example in form validation. Also avoid the use when the expensive update is already optimized, for example using memoization.

Description
All the extra information about this section

LESSON: DEEP DIVE INTO <STRONG>USETRANSITION</STRONG> HOOK IN REACT 1. INTRODUCTION: WHY DO WE NEED <STRONG>USETRANSITION</STRONG>? Imagine you’re building a search feature for a large dataset. As the user types, the UI updates with search results. However, if rendering the results is slow, the UI may feel laggy. How can we ensure a smooth, responsive experience? This is where React’s useTransition hook helps. It allows us to prioritize urgent updates (like typing) while deferring expensive updates (like rendering a long list). This keeps the app feeling snappy and interactive. REAL-WORLD SCENARIO Let’s say you have an app where users filter a list of products as they type. Without useTransition, every keystroke immediately triggers a re-render, which can slow down typing. Using useTransition, we can ensure that: * Typing remains fast (high-priority updates). * Filtering updates the list asynchronously (low-priority updates). -------------------------------------------------------------------------------- 2. UNDERSTANDING <STRONG>USETRANSITION</STRONG> HOW DOES <STRONG>USETRANSITION</STRONG> WORK? useTransition lets us mark updates as non-blocking, meaning React won’t prioritize them over urgent interactions (like typing or clicking). It returns two values: jsx CopyEdit const [isPending, startTransition] = useTransition(); * <strong>isPending</strong>: Boolean that tells us if a transition is ongoing. Useful for showing a loading state. * <strong>startTransition</strong>: A function that wraps low-priority updates. -------------------------------------------------------------------------------- 3. EXAMPLE: SLOW FILTERING WITHOUT <STRONG>USETRANSITION</STRONG> PROBLEM: UI FREEZES WHEN TYPING Without useTransition, every keystroke triggers a blocking update, making typing slow when filtering a large dataset. import React, { useState } from "react"; const products = Array.from({ length: 10000 }, (_, i) => `Product ${i + 1}`); function ProductList() { const [query, setQuery] = useState(""); const [filteredProducts, setFilteredProducts] = useState(products); const handleSearch = (e) => { setQuery(e.target.value); // Expensive operation: filtering 10,000 items every keystroke setFilteredProducts(products.filter((p) => p.includes(e.target.value))); }; return ( <div> <input type="text" value={query} onChange={handleSearch} placeholder="Search..." /> <ul> {filteredProducts.map((product) => ( <li key={product}>{product}</li> ))} </ul> </div> ); } export default ProductList; ISSUE * As users type, React blocks the UI to update filteredProducts. * The input lags when typing quickly. -------------------------------------------------------------------------------- 4. SOLUTION: USING <STRONG>USETRANSITION</STRONG> FOR A SMOOTHER UI KEY FIX: WRAP FILTERING IN <STRONG>STARTTRANSITION</STRONG> import React, { useState, useTransition } from "react"; const products = Array.from({ length: 10000 }, (_, i) => `Product ${i + 1}`); function ProductList() { const [query, setQuery] = useState(""); const [filteredProducts, setFilteredProducts] = useState(products); const [isPending, startTransition] = useTransition(); const handleSearch = (e) => { setQuery(e.target.value); // Move expensive filtering inside startTransition startTransition(() => { setFilteredProducts(products.filter((p) => p.includes(e.target.value))); }); }; return ( <div> <input type="text" value={query} onChange={handleSearch} placeholder="Search..." /> {isPending && <p>Loading...</p>} {/* Show a loading state */} <ul> {filteredProducts.map((product) => ( <li key={product}>{product}</li> ))} </ul> </div> ); } export default ProductList; WHY THIS WORKS? * Typing remains instant: The UI updates query immediately. * Filtering is deferred: React processes it in the background. * The UI never freezes, even with 10,000+ items. * A loading indicator (<strong>isPending</strong>) improves UX. -------------------------------------------------------------------------------- 5. WHEN TO USE <STRONG>USETRANSITION</STRONG>? ✅ Use useTransition when: * You have expensive computations (e.g., filtering, sorting, data-heavy UI updates). * You want to prioritize user interactions (like typing, clicking). ❌ Avoid useTransition if: * Updates must be immediate (e.g., form validation, real-time UI changes). * The expensive update is already optimized via memoization or virtualization. -------------------------------------------------------------------------------- 6. SUMMARY * useTransition prioritizes urgent updates while deferring expensive ones. * It keeps the UI responsive and smooth. * Example: Filtering a large list while typing remains instant. * Use it only when needed, especially for CPU-heavy UI updates.
Maggie

Discuss with Maggie
Use the power of generative AI to interact with course content

Maggie is a generative AI that can help you understand the course content better. You can ask her questions about the lecture, and she will try to answer them. You can also see the questions asked by other students and her responses.

Discuss with Others
Ask questions, share your thoughts, and discuss with other learners

Join the discussion to ask questions, share your thoughts, and discuss with other learners
Setup
React Fundamentals
10 points
Next.js
10 points
Advanced React
Databases
10 points
React Hooks
Authentication and Authorisation
10 points
APIs
CI/CD and DevOps
Testing React
Advanced Topics