Course contentsShow
← React
Lesson 1607 of 2,39639. Server Components in PracticeFree lesson

Server Actions in Non-Form Contexts: startTransition

Wrap Server Action calls in startTransition when invoking from event handlers to mark the update as non-urgent.

Server Actions in Non-Form Contexts: startTransition

What you'll learn: How to invoke Server Actions from event handlers like onClick using startTransition to tell React the update isn't urgent.

The Problem with Direct Calls

When you call a Server Action from a <form action>, React handles everything automatically. But what about calling Server Actions from a button's onClick handler, or a timer, or any other event? You can call them directly, but this blocks the UI while waiting for the server response—not ideal for user experience.

What startTransition Does

startTransition marks a state update as non-urgent, allowing React to keep the UI responsive while the server processes your action. Think of it like putting a task in the "background" queue—the user can still interact with other parts of your app while waiting.

'use client'
import { startTransition } from 'react'
import { likePost } from './actions'

function LikeButton({ postId }: { postId: string }) {
  const handleLike = () => {
    startTransition(async () => {
      await likePost(postId)
    })
  }

  return <button onClick={handleLike}>Like</button>
}

Why This Matters

Without startTransition, the entire UI could freeze while the Server Action runs. With it, React knows this update can be interrupted if something more urgent happens (like typing in an input field). The user sees the interface remain responsive, even though work is happening on the server.

The Pattern

Always wrap Server Action calls in startTransition when invoking from:

  • onClick handlers
  • onMouseEnter or other DOM events
  • Timers like setTimeout
  • Any non-form context where the action is triggered by user interaction

Key Takeaway: Use startTransition to wrap Server Action calls in event handlers, marking them as non-urgent updates that won't block the UI while the server responds.