Performance: Server action database mutations
This affects the time to update data on the server and how quickly the UI reflects those changes, impacting interaction responsiveness and perceived speed.
let dbConnection; export async function updateUser(data) { if (!dbConnection) { dbConnection = await db.connect(); } await db.users.updateOne({ id: data.id }, { $set: data }); // Keep connection open for batch mutations } // Debounce input to reduce calls
export async function updateUser(data) { await db.connect(); await db.users.updateOne({ id: data.id }, { $set: data }); await db.disconnect(); } // Called on every user input change triggering multiple server actions rapidly
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Connect/disconnect DB per mutation | N/A | N/A | Blocks UI update 200-500ms | [X] Bad |
| Reuse DB connection and batch mutations | N/A | N/A | Blocks UI update <50ms | [OK] Good |
await addUser({ name: 'Alice' }) if the database is empty? 'use server';
async function addUser(user) {
await db.users.create({ data: user });
return await db.users.count();
}'use server';
export async function updateUser(id, data) {
await db.users.update({ where: { id }, data });
} 'use server';
async function deleteUserIfNoOrders(userId) {
const orders = await db.orders.findMany({ where: { userId, status: 'active' } });
if (orders.length === 0) {
await db.users.delete({ where: { id: userId } });
return 'Deleted';
}
return 'Has active orders';
}Pass the test and this pattern moves unknown