Inertia.js 2.0 bridges the gap between Laravel backend and modern JavaScript frontend frameworks like React and Vue, offering a seamless way to build single-page applications (SPAs) without the complexity of traditional API-driven architectures. Let's explore its key features and capabilities in detail.
What's New in Inertia 2.0?
Inertia 2.0 introduces several groundbreaking features that enhance the development experience:
- Server-side rendering (SSR) support
- Enhanced form handling
- Improved asset loading
- Better state management
- Advanced routing capabilities
Let's dive into each major aspect of working with Inertia 2.0.
Pages and Components
In Inertia, pages are simply React/Vue components that map to your Laravel routes. Here's how to create a basic page:
// resources/js/Pages/Users/Index.jsx
import { Head } from '@inertiajs/react'
export default function Users({ users }) {
return (
<>
<Head title="Users List" />
<div className="container">
{users.map(user => (
<div key={user.id}>
{user.name}
</div>
))}
</div>
</>
)
}
Routing and Navigation
Inertia seamlessly integrates with Laravel's routing system while providing client-side navigation:
// web.php
Route::get('/users', [UserController::class, 'index'])
->name('users.index');
// Client-side navigation
import { Link } from '@inertiajs/react'
function Navigation() {
return (
<Link
href={route('users.index')}
className="nav-link"
preserveScroll={true}
>
Users
</Link>
)
}
Forms and Data Handling
Inertia 2.0 provides enhanced form handling with automatic CSRF protection and validation:
import { useForm } from '@inertiajs/react'
export default function CreateUser() {
const { data, setData, post, processing, errors } = useForm({
name: '',
email: '',
password: ''
})
function handleSubmit(e) {
e.preventDefault()
post(route('users.store'))
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={data.name}
onChange={e => setData('name', e.target.value)}
/>
{errors.name && <div>{errors.name}</div>}
<button disabled={processing}>Submit</button>
</form>
)
}
File Uploads
Inertia 2.0 simplifies file uploads with progress tracking:
import { useForm } from '@inertiajs/react'
export default function FileUpload() {
const { data, setData, post, progress } = useForm({
document: null,
})
function submit(e) {
e.preventDefault()
post(route('documents.store'), {
forceFormData: true
})
}
return (
<form onSubmit={submit}>
<input
type="file"
onChange={e => setData('document', e.target.files[0])}
/>
{progress && (
<progress value={progress.percentage} max="100">
{progress.percentage}%
</progress>
)}
</form>
)
}
Shared Data and Props
Inertia allows sharing data across all components:
// AppServiceProvider.php
public function boot()
{
Inertia::share([
'app' => [
'name' => config('app.name'),
],
'auth' => fn () => [
'user' => Auth::user() ? [
'id' => Auth::user()->id,
'name' => Auth::user()->name,
] : null,
],
]);
}
Partial Reloads and Deferred Props
Inertia 2.0 introduces efficient partial page reloads and deferred prop loading:
// Partial reload example
import { router } from '@inertiajs/react'
function refreshComments() {
router.reload({ only: ['comments'] })
}
// Deferred props
export default function Show({ user, posts }) {
return (
<div>
<h1>{user.name}</h1>
<Suspense fallback={<div>Loading posts...</div>}>
<Posts posts={posts} />
</Suspense>
</div>
)
}
Show.deferred = {
posts: true
}
State Management
Inertia 2.0 provides built-in state preservation:
import { router } from '@inertiajs/react'
router.visit('/users', {
preserveState: true,
preserveScroll: true,
only: ['users']
})
Pros and Cons of Using Inertia 2.0
Pros | Cons |
---|---|
Seamless Laravel integration | Learning curve for new developers |
No API boilerplate needed | Limited to server-side routing |
Full-stack developer experience | Tighter coupling between frontend and backend |
Built-in security features | May not fit all use cases (e.g., mobile apps) |
Progressive enhancement | Initial page load might be slower |
SEO-friendly with SSR | Requires server-side rendering setup |
Automatic asset versioning | Framework-specific limitations |
Advanced Features
Prefetching
Improve perceived performance with link prefetching:
import { Link } from '@inertiajs/react'
<Link href="/users" prefetch>
Users
</Link>
Polling
Implement real-time updates with polling:
export default function Dashboard({ stats }) {
useEffect(() => {
const interval = setInterval(() => {
router.reload({ only: ['stats'] })
}, 3000)
return () => clearInterval(interval)
}, [])
return <div>{stats.activeUsers} active users</div>
}
Load When Visible
Optimize performance by loading content only when visible:
import { useIntersectionObserver } from '@inertiajs/react'
export default function LazyContent() {
const { ref, isVisible } = useIntersectionObserver()
useEffect(() => {
if (isVisible) {
// Load content
}
}, [isVisible])
return <div ref={ref}>{/* Content */}</div>
}
Best Practices and Tips
- Always use named routes for consistency
- Implement proper error handling
- Use type checking (TypeScript) for better development experience
- Implement proper loading states
- Optimize asset bundling
- Use proper code splitting
- Implement proper caching strategies
Remember to keep your dependencies updated and follow the official documentation for the most current best practices and features. Inertia 2.0 continues to evolve with new features and improvements, making it an excellent choice for modern Laravel applications requiring rich client-side interactions.
This comprehensive overview covers the main aspects of working with Inertia 2.0, but there's always more to explore in the official documentation and community resources.
Official Documentation & Resources
- Inertia.js Official Documentation - Core concepts and API reference
- Laravel Integration Guide - Server-side adapter configuration
- Client-Side Setup - React/Vue initialization
- SSR Documentation - Server-side rendering implementation
- Form Handling - Advanced form processing guide
Community Resources
- Inertia.js Discord Community - Official community server
- Laracasts Inertia Series - Video tutorials
- Inertia.js GitHub Repository - Source code and issues
- Inertia.js Ecosystem - Community packages and extensions
Tutorials & Articles
- Getting Started with Inertia 2.0 - Step-by-step guide
- Authentication Patterns - Session management strategies
- Advanced State Management - Cross-page state sharing
- File Uploads Guide - Handling file uploads with progress
- SPA vs Inertia Comparison - Architectural analysis
Tools & Packages
- Inertia DevTools - Browser extension for debugging
- Ping CRM Demo - Reference implementation
- Laravel Jetstream - Production-ready starter kit
- Inertia.js Preset - Laravel installation helper
- Form Helper Library - Advanced form handling utilities
Pro Tip: Always check the Inertia.js Upgrade Guide when moving between versions, and consider using the @inertiajs/progress package for navigation indicators.
Top comments (2)
I'm sharing my Laravel + Vue + Inertia project for beginners in case anyone wants to learn this stack:
github.com/perisicnikola37/laravel...
Thanks for the share @perisicnikola37 🤝