xonecas.io
556
Bn

bees-nest / files

bees-nest / .opencode / skills / vercel-react-best-practices / rules / rendering-usetransition-loading.md

2.0 KB
1---
2title: Use useTransition Over Manual Loading States
3impact: LOW
4impactDescription: reduces re-renders and improves code clarity
5tags: rendering, transitions, useTransition, loading, state
6---
7
8## Use useTransition Over Manual Loading States
9
10Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
11
12**Incorrect (manual loading state):**
13
14```tsx
15function SearchResults() {
16  const [query, setQuery] = useState('')
17  const [results, setResults] = useState([])
18  const [isLoading, setIsLoading] = useState(false)
19
20  const handleSearch = async (value: string) => {
21    setIsLoading(true)
22    setQuery(value)
23    const data = await fetchResults(value)
24    setResults(data)
25    setIsLoading(false)
26  }
27
28  return (
29    <>
30      <input onChange={(e) => handleSearch(e.target.value)} />
31      {isLoading && <Spinner />}
32      <ResultsList results={results} />
33    </>
34  )
35}
36```
37
38**Correct (useTransition with built-in pending state):**
39
40```tsx
41import { useTransition, useState } from 'react'
42
43function SearchResults() {
44  const [query, setQuery] = useState('')
45  const [results, setResults] = useState([])
46  const [isPending, startTransition] = useTransition()
47
48  const handleSearch = (value: string) => {
49    setQuery(value) // Update input immediately
50    
51    startTransition(async () => {
52      // Fetch and update results
53      const data = await fetchResults(value)
54      setResults(data)
55    })
56  }
57
58  return (
59    <>
60      <input onChange={(e) => handleSearch(e.target.value)} />
61      {isPending && <Spinner />}
62      <ResultsList results={results} />
63    </>
64  )
65}
66```
67
68**Benefits:**
69
70- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
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
75Reference: [useTransition](https://react.dev/reference/react/useTransition)