Published on

Nesting useTransition

Authors
  • avatar
    Name
    Christina Yang
    Twitter

I tested nesting two useTransition hooks

// simplified version of my test
const [isOuterPending, startOuterTransition] = useTransition()
const [isInnerPending, startInnerTransition] = useTransition()

const addLog = (message: string) => {
    const timestamp = Date.now()
    console.log(`[${timestamp}] ${message}`)
}

// Track outer transition pending state changes
useEffect(() => {
    addLog(`🔄 Outer transition pending changed: ${isOuterPending}`)
}, [isOuterPending])

// Track inner transition pending state changes
useEffect(() => {
    addLog(`⏳ Inner transition pending changed: ${isInnerPending}`)
}, [isInnerPending])

startOuterTransition(() => {
    // Start inner transition
    startInnerTransition(async () => {
        // Simulate a nested update
        await delay(5000)
    })
})

return (
    <div className="p-3 bg-gray-100 rounded">
        <h3 className="text-sm font-semibold mb-2">Transition Status</h3>
        <div className="space-y-1 text-sm">
            <div className={`flex items-center ${isOuterPending ? 'text-blue-600' : 'text-gray-500'}`}>
                <span className="w-4 h-4 mr-2">{isOuterPending ? '🔄' : '⭕'}</span>
                Outer Transition: {isOuterPending ? 'Pending' : 'Idle'}
            </div>
            <div className={`flex items-center ${isInnerPending ? 'text-orange-600' : 'text-gray-500'}`}>
                <span className="w-4 h-4 mr-2">{isInnerPending ? '⏳' : '⭕'}</span>
                Inner Transition: {isInnerPending ? 'Pending' : 'Idle'}
            </div>
        </div>
    </div>
)

isOuterPending and isInnerPending were updated at the exact same time, both waiting 5s.

Not sure if I missed something, but it seems like the outer useTransition waits for the inner one to finish before it resolves, as long as the inner startTransition is an async function.

Create an ecard at CelebrateThisMortal.comBe more productive with Planda