Search code examples
next.jsserver-action

Trouble Understanding the Benefit/Point of Server Actions in Next.js


I don't understand the importance of Server Actions in Next.js. For example take a look at the following code.

import prisma from '@/utils/db';

const PrismaExamplePage: React.FunctionComponent = async() => {
    await prisma.task.create({
        data: {
            name: 'Testing Something Out Right Now.'
        }
    });
    return (
        <h1>Prisma Example Page</h1>
    );
}

export default PrismaExamplePage;

Everything works. Then I see people do the same thing using Server Actions

import prisma from '@/utils/db';

const createTask = async() => {
    "use server";
    await prisma.task.create({
        data: {
            name: 'Testing Something Out Right Now.'
        }
    });
}

const PrismaExamplePage: React.FunctionComponent = async() => {
    await createTask();
    return (
        <h1>Prisma Example Page</h1>
    );
}

export default PrismaExamplePage;

What is the difference between me using Server Actions and not using Server Actions. I don't see the benefit or the point

I've heard some people argue that it makes the code readable but thats not a good answer. Because I can also make the code more readable and not use a server action.

import prisma from '@/utils/db';

const createTask = async() => {
    await prisma.task.create({
        data: {
            name: 'Testing Something Out Right Now.'
        }
    });
}
    
const PrismaExamplePage: React.FunctionComponent = async() => {
    await createTask();
    return (
        <h1>Prisma Example Page</h1>
    );
}
    
export default PrismaExamplePage;

Solution

  • some benefit of server actions :

    • Reduced Client-side JavaScript: Next.js and React are moving in the direction of minimizing the client side bundle by offloading logic to the server. Next.js has enabled us to move a lot of code to the server, but we were still mostly building forms on the client. That changes with server actions!
    • Enhanced user experience: With features like optimistic updates and progressive enhancement, developers can create applications that feel more responsive and seamless. Users no longer need to wait for server responses to see the effects of their actions, and forms remain interactive even without JavaScript, leading to a better overall user experience even before the client hydrates.
    • Great developer experience: Server Actions make it seamless to offload data updates to the server, which would’ve required an API in the past. The APIs that Next.js and React provide make it really easy to work with.