Performant real-time state management for React and TypeScript
Performant real-time state management for React and TypeScript
Koota is an ECS-based state management library optimized for real-time apps, games, and XR experiences. Use as much or as little as you need.
npm i kootaThe official AI agent skill can be installed from this repo. Read more about skills here.
npx skills add pmndrs/kootaTraits are the building blocks of your state. They represent slices of data with specific meanings.
import { trait } from 'koota'
// Basic trait with default values
const Position = trait({ x: 0, y: 0 })
const Velocity = trait({ x: 0, y: 0 })
// Trait with a callback for initial value
// ⚠️ Must be an object
const Mesh = trait(() => new THREE.Mesh())
// Tag trait (no data)
const IsActive = trait()Entities are spawned in a world. By adding traits to an entity they gain content.
import { createWorld } from 'koota'
const world = createWorld()
const player = world.spawn(Position, Velocity)
// Initial values can be passed in to the trait by using it as a function
const goblin = world.spawn(Position({ x: 10, y: 10 }), Velocity, Mesh)Queries fetch entities sharing traits (archetypes). Use them to batch update entities efficiently.
// updateEach mutates and writes back to stores
// Run this in a loop
world.query(Position, Velocity).updateEach(([position, velocity]) => {
position.x += velocity.x * delta
position.y += velocity.y * delta
})
// For read-only operations with no mutation, use readEach
const data = []
world.query(Position, Velocity).readEach(([position, velocity]) => {
data.push({ x: position.x, y: position.y })
})Traits can be used reactively inside of React components.
import { WorldProvider, useQuery, useTrait } from 'koota/react'
// Wrap your app in WorldProvider
createRoot(document.getElementById('root')!).render(
);
function RocketRenderer() {
// Reactively update whenever the query updates with new entities
const rockets = useQuery(Position, Velocity)
return rockets.map((entity) => )
}
function RocketView({ entity }) {
// Observes this entity's position trait and reactively updates when it changes
const position = useTrait(entity, Position)
return (
)
}Use actions to safely modify Koota from inside of React in either effects or events.
…Or access world directly and use it.
const world = useWorld()
useEffect(() => {
const entity = world.spawn(Velocity, Position)
return () => entity.destroy()
})Koota supports relations between entities using the relation function. Relations allow you to build graphs by creating connections between entities with efficient queries.
const ChildOf = relation()
const parent = world.spawn()
const child = world.spawn(ChildOf(parent))
const entity = world.queryFirst(ChildOf(parent)) // Returns childA relation is typically owned by the entity that needs to express it. The source is the entity that has the relation added, and the target is the entity it points to.
flowchart BT
subgraph Parent
end
subgraph childA["Child"]
COA["ChildOf(Parent)"]
end
subgraph childB["Child"]
COB["ChildOf(Parent)"]
end
COA --> Parent
COB --> ParentIn child.add(ChildOf(parent)), child is the source and parent is the target. This design means the parent doesn't need to know about its children, instead children care about their parent, optimzing batch queries.
Relations can contain data like any trait.
const Contains = relation({ store: { amount: 0 } })
const inventory = world.spawn()
const gold = world.spawn()
// Pass initial data when adding
inventory.add(Contains(gold, { amount: 10 }))
// Update data with set
inventory.set(Contains(gold), { amount: 20 })
// Read data with get
const data = inventory.get(Contains(gold)) // { amount: 20 }Relations can automatically destroy related entities when their counterpart is destroyed using the autoDestroy option.
Destroy orphans. When a target is destroyed, destroy all sources pointing to it. This is commonly used for hierarchies when you want to clean up any detached graphs. It can be enabled with the 'orphan' or 'source' option.
const ChildOf = relation({ autoDestroy: 'orphan' }) // Or 'source'
const parent = world.spawn()
const child = world.spawn(ChildOf(parent))
const grandchild = world.spawn(ChildOf(child))
parent.destroy()
world.has(child) // False, the child and grandchild are destroyed tooDestroy targets. When a source is destroyed, destroy all its targets.
const Contains = relation({ autoDestroy: 'target' })
const container = world.spawn()
const itemA = world.spawn()
const itemB = world.spawn()
container.add(Contains(itemA), Contains(itemB))
container.destroy()
world.has(itemA) // False, items are destroyed with containerExclusive relations ensure each entity can only have one target.
const Targeting = relation({ exclusive: true })
const hero = world.spawn()
const rat = world.spawn()
const goblin = world.spawn()
hero.add(Targeting(rat))
hero.add(Targeting(goblin))
hero.has(Targeting(rat)) // False
hero.has(Targeting(goblin)) // True⚠️ Experimental
This API is experimental and may change in future versions. Please provide feedback on GitHub or Discord.
Ordered relations maintain a list of related entities with bidirectional sync.
A query like world.query(ChildOf(parent)) returns a flat list of children without any ordering. If you need an ordered list, you'd have to store an order field and sort every time you query.
An ordered relation solves this by caching the order on the target. It's a trait added to the parent that maintains a view of all entities targeting it.
flowchart BT
subgraph Parent
OC["OrderedChildren → [Child B, Child A]"]
end
subgraph childA["Child A"]
COA["ChildOf(Parent)"]
end
subgraph childB["Child B"]
COB["ChildOf(Parent)"]
end
COA --> Parent
COB --> Parentimport { relation, ordered } from 'koota'
const ChildOf = relation()
const OrderedChildren = ordered(ChildOf)
const parent = world.spawn(OrderedChildren)
const children = parent.get(OrderedChildren)
children.push(child1) // adds ChildOf(parent) to child1
children.splice(0, 1) // removes ChildOf(parent) from child1
// Bidirectional sync works both ways
child2.add(ChildOf(parent)) // child2 automatically added to listOrdered relations support array methods like push(), pop(), shift(), unshift(), and splice(), plus special methods moveTo() and insert() for precise control. Changes to the list automatically sync with relations, and vice versa, as well as emit change events.
⚠️ Performance note
Ordered relations requires additional bookkeeping where the cost of ordering is paid during structural changes (add, remove, move) instead of at query time. Use ordered relations only when entity order is essential or when hierarchical search (looping over children) is necessary.
Relations can be queried with specific targets and wildcard targets using *.
const gold = world.spawn()
const silver = world.spawn()
const inventory = world.spawn(Contains(gold), Contains(silver))
const targets = inventory.targetsFor(Contains) // Returns [gold, silver]
const chest = world.spawn(Contains(gold))
const containsSilver = world.query(Contains(silver)) // Returns [inventory]
const containsAnything = world.query(Contains('*')) // Returns [inventory, chest]A query nested in a relation can be used to filter target entities instead of naming one specific target. Use them when you want to ask for relations pointing at "any player", "any active parent", or "any rare item".
const IsRare = trait()
silver.add(IsRare)
const containsRareItems = world.query(Contains(IsRare))
const equippedOnAngryGoblin = world.query(EquippedOn(Goblin, IsAngry))A relation targets a specific entity, so we need to likewise remove relations with specific entities.
// Add a specific relation
player.add(Likes(apple))
player.add(Likes(banana))
// Remove that same relation
player.remove(Likes(apple))
player.has(apple) // false
player.has(banana) // trueHowever, a wildcard can be used to remove all relations of a kind — for all targets — from an entity.
player.add(Likes(apple))
player.add(Likes(banana))
// Remove all Likes relations
player.remove(Likes('*'))
player.has(apple) // false
player.has(banana) // falseRelations work with tracking modifiers to detect when entities gain, lose, or update relations. Changes can only be tracked on relations that have a store.
import { createAdded, createRemoved, createChanged } from 'koota'
const Added = createAdded()
const Removed = createRemoved()
const Changed = createChanged()
const ChildOf = relation({ store: { priority: 0 } })
// Track when any entity adds the ChildOf relation
const newChildren = world.query(Added(ChildOf))
// Track when any entity removes the ChildOf relation
const orphaned = world.query(Removed(ChildOf))
// Track when relation data changes for any target
const updated = world.query(Changed(ChildOf))Note
Tracking modifiers do not accept pairs directly such as
Changed(ChildOf(parent)). Instead, pass the base relation to the modifier and add the pair as a separate query parameter to filter by target.
const parent = world.spawn()
// Filter changed entities by a specific target
const changedChildren = world.query(Changed(ChildOf), ChildOf(parent))
// Filter changed entities by the target's traits
const changedPlayerChildren = world.query(Changed(ChildOf), ChildOf(IsPlayer))Relations emit events per pair. This makes it easy to know exactly which target was involved.
onAdd(Relation, (entity, target) => {}) triggers when entity.add(Relation(target)) is called.onRemove(Relation, (entity, target) => {}) triggers when entity.remove(Relation(target)) is called.onChange(Relation, (entity, target) => {}) triggers when relation store data is updated with entity.set(Relation(target), data) (only for relations created with a store).const ChildOf = relation({ store: { priority: 0 } })
const unsubAdd = world.onAdd(ChildOf, (entity, target) => {})
const unsubRemove = world.onRemove(ChildOf, (entity, target) => {})
const unsubChange = world.onChange(ChildOf, (entity, target) => {})
const parent = world.spawn()
const child = world.spawn()
child.add(ChildOf(parent)) // onAdd(child, parent)
child.set(ChildOf(parent), { priority: 1 }) // onChange(child, parent)
child.remove(ChildOf(parent)) // onRemove(child, parent)Hooks also accept relation pairs for target-specific filtering. ChildOf(parent) only fires for that specific target, while ChildOf('*') fires for any target (equivalent to passing the relation itself).
// Only fires when a ChildOf relation to this specific parent is added
world.onAdd(ChildOf(parent), (entity, target) => {})
// Fires for any ChildOf addition, the same as passing the ChildOf trait
world.onAdd(ChildOf('*'), (entity, target) => {})Modifiers are used to filter query results enabling powerful patterns. All modifiers can be mixed together.
The Not modifier excludes entities that have specific traits from the query results.
import { Not } from 'koota'
const staticEntities = world.query(Position, Not(Velocity))By default all query parameters are combined with log
No open issues yet, or sync has not completed.