TanStackT
TanStack4mo ago
7 replies
ripe-gray

What is the purpose of useServerFn, all works without it

At What are Server Functions? page we have example of server function that can be used with useQuery (from TanStack Query, to fetch data from endpoint).

Example is as follows:
const getServerPosts = createServerFn().handler(async () => {...});

// In a component
function PostList() {
  const getPosts = useServerFn(getServerPosts)

  const { data } = useQuery({
    queryKey: ['posts'],
    queryFn: () => getPosts(),
  })
}


However, if I remove useServerFn and use getServerPosts directly:
const getServerPosts = createServerFn().handler(async () => {...});

// In a component
function PostList() {
  const { data } = useQuery({
    queryKey: ['posts'],
    queryFn: () => getServerPosts(),
  })
}


Then everything keeps working just as fine. When I inspect natwork requests in dev tools, there's nothing suspicious going on, I mean the requests are the same, payloads returned are also the same, the application itself keeps working fine.

So the question is what is the purpose of useServerFn hooks and what it help us with?
What are Server Functions? Server functions let you define server-only logic that can be called from anywhere in your application loaders, components, hooks, or other server functions. They run on the...
Server Functions | TanStack Start React Docs
Was this page helpful?