How change detection works with objects and arrays
mainKoota performs shallow comparison for change detection, similar to React.
- Objects and Arrays: A change is only detected if the reference changes (i.e., a new object or array is assigned to the store).
- Mutations: Mutating an existing array or object (e.g., using
.push()) will not be detected by the shallow comparison because the reference remains the same.
To ensure changes are detected, you can either:
- Use Immutability: Replace the existing object/array with a new one (e.g., using the spread operator).
- Manual Flagging: Mutate the object for better performance and then manually call
entity.changed()to signal that a change has occurred.
// ❌ Mutation is NOT detected (shallow comparison passes)
world.query(Inventory).updateEach(([inventory]) => {
inventory.items.push(item)
})
// ✅ Immutability IS detected (new array reference)
world.query(Inventory).updateEach(([inventory]) => {
inventory.items = [...inventory.items, item]
})
// ✅ Manual flagging IS detected (mutation + manual signal)
world.query(Inventory).updateEach(([inventory], entity) => {
inventory.items.push(item)
entity.changed()
})