| 1 | --- |
| 2 | title: Use useTransition Over Manual Loading States |
| 3 | impact: LOW |
| 4 | impactDescription: reduces re-renders and improves code clarity |
| 5 | tags: rendering, transitions, useTransition, loading, state |
| 6 | --- |
| 7 | |
| 8 | ## Use useTransition Over Manual Loading States |
| 9 | |
| 10 | Use `useTransition` instead of manual `useState` for loading states. This provides built-in ` |
| 11 | |
| 12 | **Incorrect (manual loading state):** |
| 13 | |
| 14 | ```tsx |
| 15 | function SearchResults() { |
| 16 | const [query, |
| 17 | const [results, |
| 18 | const [isLoading, |
| 19 | |
| 20 | const handleSearch = |
| 21 | setIsLoading(true); |
| 22 | setQuery(value); |
| 23 | const data = |
| 24 | setResults(data); |
| 25 | setIsLoading(false); |
| 26 | }; |
| 27 | |
| 28 | return ( |
| 29 | <> |
| 30 | <input onChange={ |
| 31 | {isLoading && <Spinner |
| 32 | <ResultsList results= |
| 33 | </> |
| 34 | ); |
| 35 | } |
| 36 | ``` |
| 37 | |
| 38 | **Correct (useTransition with built-in pending state):** |
| 39 | |
| 40 | ```tsx |
| 41 | import { useTransition, useState |
| 42 | |
| 43 | function SearchResults() { |
| 44 | const [query, |
| 45 | const [results, |
| 46 | const [isPending, |
| 47 | |
| 48 | const handleSearch = |
| 49 | setQuery(value); |
| 50 | |
| 51 | startTransition(async () |
| 52 | // Fetch and update results |
| 53 | const data = |
| 54 | setResults(data); |
| 55 | }); |
| 56 | }; |
| 57 | |
| 58 | return ( |
| 59 | <> |
| 60 | <input onChange={ |
| 61 | {isPending && <Spinner |
| 62 | <ResultsList results= |
| 63 | </> |
| 64 | ); |
| 65 | } |
| 66 | ``` |
| 67 | |
| 68 | **Benefits:** |
| 69 | |
| 70 | - **Automatic pending state**: No need to manually manage |
| 71 | - **Error resilience**: Pending state correctly resets even if the transition throws |
| 72 | - **Better responsiveness**: Keeps the UI responsive during updates |
| 73 | - **Interrupt handling**: New transitions automatically cancel pending ones |
| 74 | |
| 75 | Reference: [useTransition](https://react.dev/reference/react/useTransition |