Livewire

JavaScript Hooks in Livewire v4

February 01, 2026 1 min read 23 views

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

Request Lifecycle Hooks

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

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

// 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();
    }
});
Share this post:

Related Posts

Comments (0)

Please log in to leave a comment. Log in

No comments yet. Be the first to comment!