Comprensión de Next.js 14 Componentes del servidor y acciones del servidor
Web Development28 de diciembre de 202510 min de lectura6 vistas
Next.jsReactServer ComponentsServer ActionsTypeScriptPerformance
Compartir:
Understanding Next.js 14 Server Components and Server Actions
Next.js 14 introduces Server Components and Server Actions, fundamentally changing how we build React applications. Let's explore these game-changing features.
What Are Server Components?
Server Components are React components that run exclusively on the server. They never send JavaScript to the client. ### Benefits:
- ⚡ Zero client-side JavaScript
- 🚀 Faster initial page loads
- 💾 Direct database access
- 🔒 Enhanced security
- 📦 Smaller bundle sizes
Server vs Client Components
Server Components (Default)
// app/products/page.tsx async function ProductsPage() { // Direct database access! const products = await db.products.findMany(); return ( <div> {products.map(product => ( <ProductCard key={product.id} {...product} /> ))} </div> ); } ``` ### Client Components ```jsx 'use client'; export function Counter() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); } ``` ## Server Actions: Forms Made Simple Server Actions let you mutate data directly from the server, without API routes. ```jsx // app/actions.ts 'use server'; export async function createProduct(formData: FormData) { const name = formData.get('name'); const price = formData.get('price'); await db.products.create({ data: { name, price: Number(price) } }); revalidatePath('/products'); } ``` ```jsx // app/products/new/page.tsx import { createProduct } from '@/app/actions'; export default function NewProduct() { return ( <form action={createProduct}> <input name="name" required /> <input name="price" type="number" required /> <button type="submit">Create</button> </form> ); } ``` ## Data Fetching Patterns ### Parallel Data Fetching ```jsx async function Page() { const [products, categories] = await Promise.all([ getProducts(), getCategories() ]); return <ProductList products={products} categories={categories} />; } ``` ### Sequential Data Fetching ```jsx async function Page({ params }) { const product = await getProduct(params.id); const relatedProducts = await getRelatedProducts(product.category); return ( <> <ProductDetail product={product} /> <RelatedProducts products={relatedProducts} /> </> ); } ``` ## Streaming with Suspense Stream content as it loads for better perceived performance: ```jsx import { Suspense } from 'react'; export default function Page() { return ( <> <Header /> <Suspense fallback={<ProductsSkeleton />}> <Products /> </Suspense> <Suspense fallback={<ReviewsSkeleton />}> <Reviews /> </Suspense> </> ); } ``` ## Best Practices 1. **Use Server Components by default** - Only use 'use client' when needed 2. **Keep Client Components small** - Push them as far down the tree as possible 3. **Use Server Actions for mutations** - Simpler than API routes 4. **Leverage streaming** - Better UX with Suspense boundaries 5. **Cache strategically** - Use revalidation to keep data fresh ## When to Use Client Components Use 'use client' when you need: - Event listeners (onClick, onChange, etc.) - Browser APIs (localStorage, window, etc.) - State hooks (useState, useReducer, etc.) - Effect hooks (useEffect, useLayoutEffect) - Custom hooks that use the above ## Conclusion Server Components and Server Actions represent the future of React development. They simplify data fetching, improve performance, and enhance security - all while reducing client-side JavaScript. Start migrating your apps to this new paradigm today! 🎉