NEOLearn

Hooks and lifecycle events

Run code when a component is added, inserted, discarded, removed or despawned, with component hooks or lifecycle observers, and keep indexes in sync.

Updated October 20, 2026

On this page

Every component goes through a lifecycle: it is added to an entity, possibly replaced with new values, and finally removed or despawned with its entity. The engine raises a lifecycle event at each step. You can react with a component hook, which belongs to the component type itself, or with an observer, which you add and remove at runtime.

The lifecycle events#

EventRaised when
AddA component is inserted on an entity that didn't have it. Spawning counts.
InsertA component is inserted, whether or not the entity already had it. Runs after Add.
DiscardA component value is about to be dropped: replaced by an insert, or removed. Runs before Remove.
RemoveA component is removed and not replaced. Despawning counts. The data is still there when it runs.
DespawnAn entity is despawned, once for each of its components. Runs before Discard and Remove.

Add and Remove mark the component appearing and disappearing. Insert and Discard mark every new value and every value thrown away, so together they capture all changes made by inserting.

Lifecycle observers#

Observe a lifecycle event with On<Add<T>>, On<Insert<T>>, On<Discard<T>>, On<Remove<T>> or On<Despawn<T>>:

Rust
use neo::prelude::*;

#[derive(Component)]
struct Mine { radius: f32 }

#[derive(Resource, Default)]
struct MineCount(u32);

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .init_resource::<MineCount>()
        .add_observer(|add: On<Add<Mine>>, mut count: ResMut<MineCount>| {
            count.0 += 1;
            info!("mine added to {}", add.entity);
        })
        .add_observer(|_remove: On<Remove<Mine>>, mut count: ResMut<MineCount>| {
            count.0 -= 1;
        })
        .run();
}

add.entity is the entity the component was added to. A tuple watches several components: On<Add<(A, B)>> runs when either is added.

Component hooks#

A hook is a plain function attached to a component type. There is at most one hook of each kind per component, and it always runs: hooks are part of what the component is, like a constructor and destructor. Declare them on the derive:

Rust
use neo::ecs::{lifecycle::HookContext, world::DeferredWorld};

#[derive(Component)]
#[component(on_add = on_add_tracked, on_remove = on_remove_tracked)]
struct Tracked;

fn on_add_tracked(mut world: DeferredWorld, HookContext { entity, .. }: HookContext) {
    world.resource_mut::<TrackedList>().0.push(entity);
}

fn on_remove_tracked(mut world: DeferredWorld, context: HookContext) {
    world.resource_mut::<TrackedList>().0.retain(|e| *e != context.entity);
}

#[derive(Resource, Default)]
struct TrackedList(Vec<Entity>);

The attributes are on_add, on_insert, on_discard, on_remove and on_despawn. You can also register hooks at runtime, before the component is first used:

Rust
fn setup(world: &mut World) {
    world
        .register_component_hooks::<Tracked>()
        .on_insert(|world, context| {
            info!("Tracked inserted on {}", context.entity);
        });
}

What a hook gets#

ArgumentWhat it is
DeferredWorldThe world, with access to components and resources, but no structural changes. Queue those with world.commands(). It can also write_message and trigger.
HookContextentity, the component's component_id, and caller, the source location when track_location is on.

Hooks or observers?#

HooksObservers
One per lifecycle event per component, fixed by the component's author.Any number, added and removed at runtime.
Plain functions with DeferredWorld.Full systems: queries, resources, run conditions.
On add: run before observers. On remove: run after them.The reverse, so hooks get the first and last word.
Slightly cheaper.Slightly more overhead, much more flexible.

Use hooks to keep a component's own invariants and indexes correct. Use observers for gameplay reactions. If you only need to notice changes eventually, change detection (Added<T>, RemovedComponents<T>) is cheaper than either.

The engine uses hooks itself: relationships such as ChildOf keep the other side (Children) up to date with on_insert and on_discard hooks. See Relationships and hierarchy.

Examples#

Run these from the engine core's workspace:

ExampleWhat it shows
cargo run --example component_hooksAll four insert and remove hooks keeping an index in sync with key presses.
cargo run --example immutable_componentsAn immutable Name-like component indexed by hooks.
cargo run --example observersAdd and Remove observers maintaining a spatial index.

Next steps#