Understanding Inertia.js 2.0: Building Modern Monolithic Applications with Laravel and React/Vue

Understanding Inertia.js 2.0: Building Modern Monolithic Applications with Laravel and React/Vue

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>
    </>
  )
}

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

ProsCons
Seamless Laravel integrationLearning curve for new developers
No API boilerplate neededLimited to server-side routing
Full-stack developer experienceTighter coupling between frontend and backend
Built-in security featuresMay not fit all use cases (e.g., mobile apps)
Progressive enhancementInitial page load might be slower
SEO-friendly with SSRRequires server-side rendering setup
Automatic asset versioningFramework-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

  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.