Updating Data in Next.js – Server Functions, Actions, and UI Revalidation

Next.js enables data updates through Server Functions, also known as Server Actions. These asynchronous functions run on the server and can be invoked from forms, buttons, or event handlers in Client Components. This article explains how to define Server Functions, invoke them, show pending states, revalidate cache, redirect users, and manage cookies—all while keeping the UI responsive and consistent.

Server FunctionsServer ActionsformActionrevalidatePathuseActionState

~4 min read · Updated Oct 25, 2025

What Are Server Functions?


Server Functions are asynchronous functions that run on the server and can be invoked from the client. In mutation contexts, they’re called Server Actions. They integrate with Next.js caching and are triggered via formAction, action, or startTransition. Only POST requests can invoke them.


Creating Server Functions


Use the 'use server' directive to mark a function as server-side. You can place it inside a function or at the top of a file:


// app/lib/actions.ts
export async function createPost(formData: FormData) {
  'use server'
  const title = formData.get('title')
  const content = formData.get('content')
  // Update data and revalidate
}

Using Server Functions in Server Components


You can inline Server Functions directly in Server Components:


// app/page.tsx
export default function Page() {
  async function createPost(formData: FormData) {
    'use server'
    // ...
  }
  return <></>
}

Invoking Server Functions in Client Components


Client Components can’t define Server Functions, but they can import and invoke them:


// app/ui/button.tsx
'use client'
import { createPost } from '@/app/actions'

export function Button() {
  return <button formAction={createPost}>Create</button>
}

Passing Actions as Props


// app/client-component.tsx
'use client'
export default function ClientComponent({ updateItemAction }) {
  return <form action={updateItemAction}>...</form>
}

Invoking Server Functions


  • Forms: Use action or formAction to submit data.
  • Event Handlers: Use onClick or useEffect to trigger updates.

Example with Form


// app/ui/form.tsx
import { createPost } from '@/app/actions'

export function Form() {
  return (
    <form action={createPost}>
      <input name="title" />
      <input name="content" />
      <button>Create</button>
    </form>
  )
}

Example with onClick


// app/like-button.tsx
'use client'
import { incrementLike } from './actions'
import { useState } from 'react'

export default function LikeButton({ initialLikes }) {
  const [likes, setLikes] = useState(initialLikes)
  return (
    <>
      <p>Total Likes: {likes}</p>
      <button onClick={async () => {
        const updatedLikes = await incrementLike()
        setLikes(updatedLikes)
      }}>
        Like
      </button>
    </>
  )
}

Showing a Pending State


Use useActionState to show a loading indicator while the Server Function is running:


// app/ui/button.tsx
'use client'
import { useActionState, startTransition } from 'react'
import { createPost } from '@/app/actions'
import { LoadingSpinner } from '@/app/ui/loading-spinner'

export function Button() {
  const [state, action, pending] = useActionState(createPost, false)
  return (
    <button onClick={() => startTransition(action)}>
      {pending ? <LoadingSpinner /> : 'Create Post'}
    </button>
  )
}

Revalidating Cache


Use revalidatePath or revalidateTag to refresh cached data after updates:


// app/lib/actions.ts
import { revalidatePath } from 'next/cache'

export async function createPost(formData) {
  'use server'
  // Update data
  revalidatePath('/posts')
}

Redirecting After Update


Use redirect to navigate after a mutation:


// app/lib/actions.ts
'use server'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'

export async function createPost(formData) {
  // Update data
  revalidatePath('/posts')
  redirect('/posts')
}

Managing Cookies


Use the cookies API inside Server Actions to get, set, or delete cookies:


// app/actions.ts
'use server'
import { cookies } from 'next/headers'

export async function exampleAction() {
  const cookieStore = await cookies()
  cookieStore.set('name', 'Delba')
  cookieStore.delete('name')
}

Using useEffect to Trigger Server Actions


Use useEffect to trigger updates on mount or dependency change:


// app/view-count.tsx
'use client'
import { incrementViews } from './actions'
import { useState, useEffect, useTransition } from 'react'

export default function ViewCount({ initialViews }) {
  const [views, setViews] = useState(initialViews)
  const [isPending, startTransition] = useTransition()

  useEffect(() => {
    startTransition(async () => {
      const updatedViews = await incrementViews()
      setViews(updatedViews)
    })
  }, [])

  return <p>Total Views: {views}</p>
}

Conclusion


Server Functions in Next.js make it easy to update data, revalidate cache, and reflect changes in the UI—all with minimal client-side complexity. Whether triggered by forms, buttons, or lifecycle hooks, these actions help keep your app fast, interactive, and consistent.


Written & researched by Dr. Shahin Siami

Related Articles

Advanced Client-Side Routing and Performance Hooks in Next.js

Next.js provides a rich set of client-side hooks and caching utilities that empower developers to build dynamic, responsive, and secure applications. From reading route parameters to tracking navigation state and reporting performance metrics, this guide walks you through the most important tools available in the App Router.

Continue

Handling Authorization and Caching in Next.js: A Developer’s Guide

Next.js introduces powerful experimental features for access control and smart caching. This guide covers the unauthorized() function for custom 401 handling, unstable_cache for persistent memoization, updateTag for instant cache invalidation, and useLinkStatus for inline navigation feedback. Learn how to use these tools to build secure, performant, and responsive applications.

Continue

redirect and refresh in Next.js — Smart Redirects and Client Refreshing via Server Actions

The redirect function in Next.js allows you to navigate users to a new route, returning either a 307 or 303 HTTP response depending on context. It works in Server Components, Client Components, Route Handlers, and Server Actions. The refresh function is used exclusively within Server Actions to refresh the client router. This article explains how both functions work, with practical examples and key considerations.

Continue

NextRequest and NextResponse in Next.js — Managing Cookies, Headers, Redirects, and Rewrites

Next.js extends the native Web Request and Response APIs with NextRequest and NextResponse, offering powerful tools for managing cookies, headers, redirects, rewrites, and JSON responses. These utilities simplify server-side logic and improve control over routing, personalization, and security. This guide walks through their capabilities with practical examples and best practices.

Continue

headers, ImageResponse, notFound, and permanentRedirect in Next.js — Request Handling, Dynamic Images, Errors, and Redirects

Next.js offers powerful tools for handling HTTP requests and responses in Server Components. The headers function lets you read incoming request headers. ImageResponse allows you to generate dynamic images using JSX and CSS. The notFound function renders a custom 404 page, and permanentRedirect enables permanent redirection to another route. This article explains how to use each feature with practical examples.

Continue

A Complete Guide to Using metadata and generateMetadata in Next.js

In modern versions of Next.js, managing page metadata is more powerful and intuitive than ever. Metadata is automatically injected into the <head> of your pages and plays a vital role in SEO, social sharing, and user experience. This guide explains the two main ways to define metadata: using the static metadata object and the dynamic generateMetadata function.

Continue