T
TanStack2mo ago
harsh-harlequin

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(),
})
}
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(),
})
}
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?
Server Functions | TanStack Start React Docs
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...
4 Replies
foreign-sapphire
foreign-sapphire2mo ago
among other things, it handles redirects if your server function throws a redirect, you need useServerFn for the redirection to work. Otherwise it'll be unhandle and just be an error
harsh-harlequin
harsh-harlequinOP2mo ago
cool, thanks for the explanation! Indeed, with throw redirect() it works, so what it does, in theory? i mean why for example, redirect does not work without it?
foreign-sapphire
foreign-sapphire2mo ago
because its just client side error catching into handling it as a navigation you'll ask "but why isnt just returning a 302 instead of an error" ? Because 302 would cause a refresh not very good
harsh-harlequin
harsh-harlequinOP2mo ago
cool thanks for explanations!

Did you find this page helpful?