Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply 62 React and Next.js performance optimization rules from Vercel Engineering
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/rendering-usetransition-loading.md
1---2title: Use useTransition Over Manual Loading States3impact: LOW4impactDescription: reduces re-renders and improves code clarity5tags: rendering, transitions, useTransition, loading, state6---78## Use useTransition Over Manual Loading States910Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.1112**Incorrect (manual loading state):**1314```tsx15function SearchResults() {16const [query, setQuery] = useState('')17const [results, setResults] = useState([])18const [isLoading, setIsLoading] = useState(false)1920const handleSearch = async (value: string) => {21setIsLoading(true)22setQuery(value)23const data = await fetchResults(value)24setResults(data)25setIsLoading(false)26}2728return (29<>30<input onChange={(e) => handleSearch(e.target.value)} />31{isLoading && <Spinner />}32<ResultsList results={results} />33</>34)35}36```3738**Correct (useTransition with built-in pending state):**3940```tsx41import { useTransition, useState } from 'react'4243function SearchResults() {44const [query, setQuery] = useState('')45const [results, setResults] = useState([])46const [isPending, startTransition] = useTransition()4748const handleSearch = (value: string) => {49setQuery(value) // Update input immediately5051startTransition(async () => {52// Fetch and update results53const data = await fetchResults(value)54setResults(data)55})56}5758return (59<>60<input onChange={(e) => handleSearch(e.target.value)} />61{isPending && <Spinner />}62<ResultsList results={results} />63</>64)65}66```6768**Benefits:**6970- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`71- **Error resilience**: Pending state correctly resets even if the transition throws72- **Better responsiveness**: Keeps the UI responsive during updates73- **Interrupt handling**: New transitions automatically cancel pending ones7475Reference: [useTransition](https://react.dev/reference/react/useTransition)76