Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
K

koota

> 前端框架
Open source

Performant real-time state management for React and TypeScript

708 stars0 likes3 views
WebsiteGitHub

About

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.

bash
npm i koota

The official AI agent skill can be installed from this repo. Read more about skills here.

bash
npx skills add pmndrs/koota

First, define traits

Traits are the building blocks of your state. They represent slices of data with specific meanings.

javascript
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()

Spawn entities

Entities are spawned in a world. By adding traits to an entity they gain content.

javascript
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)

Query and update data

Queries fetch entities sharing traits (archetypes). Use them to batch update entities efficiently.

javascript
// 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 })
})

Use in your React components

Traits can be used reactively inside of React components.

javascript
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 (
        

    )
}

Modify Koota state safely with actions

Use actions to safely modify Koota from inside of React in either effects or events.

…

Or access world directly and use it.

javascript
const world = useWorld()

useEffect(() => {
  const entity = world.spawn(Velocity, Position)
  return () => entity.destroy()
})

Advanced

Relations

Koota supports relations between entities using the relation function. Relations allow you to build graphs by creating connections between entities with efficient queries.

javascript
const ChildOf = relation()

const parent = world.spawn()
const child = world.spawn(ChildOf(parent))

const entity = world.queryFirst(ChildOf(parent)) // Returns child

A 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.

mermaid
flowchart BT
    subgraph Parent
    end
    subgraph childA["Child"]
        COA["ChildOf(Parent)"]
    end
    subgraph childB["Child"]
        COB["ChildOf(Parent)"]
    end
    COA --> Parent
    COB --> Parent

In 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.

With data

Relations can contain data like any trait.

javascript
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 }

Auto destroy

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.

javascript
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 too

Destroy targets. When a source is destroyed, destroy all its targets.

javascript
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 container

Exclusive relations

Exclusive relations ensure each entity can only have one target.

javascript
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

Ordered relations

⚠️ 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.

mermaid
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 --> Parent
javascript
import { 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 list

Ordered 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.

Querying relations

Relations can be queried with specific targets and wildcard targets using *.

javascript
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]

Relation filters

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".

javascript
const IsRare = trait()

silver.add(IsRare)

const containsRareItems = world.query(Contains(IsRare))
const equippedOnAngryGoblin = world.query(EquippedOn(Goblin, IsAngry))

Removing relations

A relation targets a specific entity, so we need to likewise remove relations with specific entities.

javascript
// 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) // true

However, a wildcard can be used to remove all relations of a kind — for all targets — from an entity.

javascript
player.add(Likes(apple))
player.add(Likes(banana))

// Remove all Likes relations
player.remove(Likes('*'))

player.has(apple) // false
player.has(banana) // false

Tracking relation changes

Relations work with tracking modifiers to detect when entities gain, lose, or update relations. Changes can only be tracked on relations that have a store.

javascript
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.

javascript
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))

Relation events

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).
javascript
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).

javascript
// 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) => {})

Query modifiers

Modifiers are used to filter query results enabling powerful patterns. All modifiers can be mixed together.

Not

The Not modifier excludes entities that have specific traits from the query results.

javascript
import { Not } from 'koota'

const staticEntities = world.query(Position, Not(Velocity))

Or

By default all query parameters are combined with log

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptdata-oriented-designdata-oriented-programmingecsentity-component-system

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架