DEV Community

Cover image for Understanding Inertia.js 2.0: A Comprehensive Guide for React and Vue Integration with Laravel
deeAjith
deeAjith

Posted on

Understanding Inertia.js 2.0: A Comprehensive Guide for React and Vue Integration with Laravel

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>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode
// Client-side navigation
import { Link } from '@inertiajs/react'

function Navigation() {
  return (
    <Link
      href={route('users.index')}
      className="nav-link"
      preserveScroll={true}
    >
      Users
    </Link>
  )
}
Enter fullscreen mode Exit fullscreen mode

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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,
        ],
    ]);
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

State Management

Inertia 2.0 provides built-in state preservation:

import { router } from '@inertiajs/react'

router.visit('/users', {
  preserveState: true,
  preserveScroll: true,
  only: ['users']
})
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
}
Enter fullscreen mode Exit fullscreen mode

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>
}
Enter fullscreen mode Exit fullscreen mode

Best Practices and Tips

  1. Always use named routes for consistency
  2. Implement proper error handling
  3. Use type checking (TypeScript) for better development experience
  4. Implement proper loading states
  5. Optimize asset bundling
  6. Use proper code splitting
  7. 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

Community Resources

Tutorials & Articles

Tools & Packages

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)

Collapse
 
perisicnikola37 profile image
Nikola Perišić

I'm sharing my Laravel + Vue + Inertia project for beginners in case anyone wants to learn this stack:
github.com/perisicnikola37/laravel...

Collapse
 
deeajith profile image
deeAjith

Thanks for the share @perisicnikola37 🤝