Understanding the Matter.js afterRemove Event

This article provides an overview of the afterRemove event in Matter.js, explaining its role in the physics engine lifecycle, how it functions within composite structures, and how to implement it for resource cleanup and state synchronization in your projects.

What is the afterRemove Event?

In Matter.js, simulation elements such as bodies, constraints, and other composites are managed within composite containers, most notably the root Matter.World (engine.world). The afterRemove event is an event dispatched by a Matter.Composite instance immediately after an object has been completely removed from that composite.

When you call Composite.remove(world, object), Matter.js first fires a beforeRemove event, detaches the object from the composite's internal lists, and then fires the afterRemove event.

Key Use Cases

The afterRemove event is typically used to manage application state and clean up resources tied to physics objects:

How to Use afterRemove

To listen for the afterRemove event, use the Matter.Events.on method to bind a callback function to the target composite or world.

// Import modules
const { Engine, World, Bodies, Composite, Events } = Matter;

const engine = Engine.create();
const world = engine.world;

// Listen for the afterRemove event on the world composite
Events.on(world, 'afterRemove', (event) => {
    // The removed entity is available via event.object
    const removedObject = event.object;
    
    console.log('Object successfully removed:', removedObject);

    // Example: Clean up custom rendering reference
    if (removedObject.renderSprite) {
        removedObject.renderSprite.destroy();
    }
});

// Create and add a body
const box = Bodies.rectangle(400, 200, 80, 80);
Composite.add(world, box);

// Remove the body from the world, triggering afterRemove
Composite.remove(world, box);

Event Data Properties

When the callback executes, it receives an event object containing:

Difference Between beforeRemove and afterRemove

While beforeRemove executes while the item is still registered within the composite, afterRemove guarantees that the composite hierarchy has already been updated. If your cleanup logic relies on verifying that the body is no longer present in composite.bodies or requires the composite's bounding limits to be recalculated, afterRemove is the appropriate hook to use.