Overview
Next.js App Router introduces a new component model that distinguishes between server and client components. This distinction is crucial for optimizing performance, reducing bundle size, and improving user experience.Server Components (Default)
Server components run on the server and are rendered before being sent to the browser. They have access to server-side resources and don’t include JavaScript in the client bundle.Key Characteristics
Server-Side Rendering
- Rendered on the server
- HTML sent to browser
- No JavaScript in client bundle
- Direct database access
Performance Benefits
- Reduced bundle size
- Faster initial page load
- Better SEO
- Enhanced security
When to Use Server Components
- Data Fetching: Fetch data from databases, APIs, or file systems
- Static Content: Display content that doesn’t change frequently
- Large Dependencies: Use libraries that are large or server-only
- Sensitive Operations: Handle operations that shouldn’t be exposed to the client
Example: Server Component
Client Components
Client components run in the browser and provide interactivity. They include JavaScript in the client bundle and can use browser APIs and React hooks.Key Characteristics
Client-Side Rendering
- Rendered in the browser
- Includes JavaScript bundle
- Hydration required
- Interactive features
Use Cases
- Event handlers
- State management
- Browser APIs
- Real-time updates
When to Use Client Components
- Interactivity: Components that need event handlers (onClick, onChange)
- Browser APIs: Access to localStorage, geolocation, camera, etc.
- State Management: Components using useState, useEffect, or other hooks
- Third-Party Libraries: Libraries that require browser APIs
Example: Client Component
The ‘use client’ Directive
The'use client'
directive tells Next.js that a component should run on the client side.
Important Rules
- Must be at the top: The directive must be the very first line in the file
- No code before it: Nothing can come before the directive
- File-level scope: Applies to the entire file and all its exports
Basic Component Composition
Server Component with Client Children
Best Practices for Module 1
Component Design
- Start with Server Components: Default to server components unless client features are needed
- Minimize Client Boundaries: Keep client components small and focused
- Use Composition: Compose server and client components effectively
- Add ‘use client’ Only When Necessary: Only use the directive when you need interactivity
Key Takeaway: The key to optimal Next.js performance is using server
components by default and only adding client components where interactivity is
required. This approach reduces bundle size and improves user experience.