Mahmoud Al-HabashOpen to new projects
  • WorkWork
  • ServicesServices
  • LabLab
  • WritingWriting
  • ContactContact
Amman--:--عربي
Writing/Livewire

JavaScript Hooks in Livewire v4

Hook into Livewire lifecycle from JavaScript.

1 February 20261 min readLivewireاقرأ بالعربية

On this page

  1. Request Lifecycle Hooks
  2. Component Lifecycle Hooks
  3. Element Hooks

Livewire v4 exposes JavaScript hooks to integrate with the component lifecycle.

Request Lifecycle Hooks

javascript
// Hook into every Livewire request
Livewire.hook('request', ({ uri, options, payload, respond, succeed, fail }) => {
    // Before request is sent
    console.log('Request starting...', payload);
    
    // After successful response
    succeed(({ status, json }) => {
        console.log('Request succeeded!', status);
    });
    
    // After failed response
    fail(({ status, content, preventDefault }) => {
        console.error('Request failed!', status);
        // Prevent default error handling
        preventDefault();
    });
});

Component Lifecycle Hooks

javascript
// When component is initialized
Livewire.hook('component.init', ({ component, cleanup }) => {
    console.log('Component initialized:', component.name);
    
    // Cleanup when component is destroyed
    cleanup(() => {
        console.log('Component destroyed');
    });
});

// Before DOM is morphed
Livewire.hook('morph.updating', ({ el, component, toEl, skip, childrenOnly }) => {
    // Skip morphing for specific elements
    if (el.hasAttribute('data-no-morph')) {
        skip();
    }
});

// After DOM is morphed
Livewire.hook('morph.updated', ({ el, component }) => {
    // Re-initialize third-party libraries
    initTooltips(el);
});

Element Hooks

javascript
// When new elements are added to DOM
Livewire.hook('element.init', ({ el, component }) => {
    // Initialize any element-specific JS
    if (el.hasAttribute('data-chart')) {
        initChart(el);
    }
});

// Before element is removed
Livewire.hook('element.removing', ({ el, component, skip }) => {
    // Cleanup before removal
    if (el.chart) {
        el.chart.destroy();
    }
});
All articles

Keep reading

  • Authorization in Livewire v4 Components1 February 20261 min read
  • Blaze Pre-Compiler: Massive Performance Gains in Livewire v41 February 20261 min read
  • Building a Bookmark Feature with Livewire v41 February 20261 min read