GitHub v1.3.1
Lesson 10

Reactive State

Trigger predictable DOM updates with direct state mutations and derived getters.

Direct Mutations

Coralite uses a reactive proxy to track changes to the state object. You don't need to call setState or useState. Simply mutate the property directly inside your event listener, and Coralite will schedule a batched microtask update.

html
Code copied!
  <template id="counter">
    <button ref="btn">Count is {{ count }}</button>
  </template>
  
  <script type="module">
    export function server () {
      return { count: 0 }
    }
  
    export async function client ({ state, refs, signal }) {
      refs('btn').addEventListener('click', () => {
        // Direct mutation triggers a DOM update
        state.count++
      }, { signal })
    }
  </script>

Derived Logic with Getters

Coralite templates only allow flat identifiers. You cannot write complex logic inside the HTML. If you need to compute a value based on state, you must use the getters block.

javascript
Code copied!
  <script type="module">
    export const getters = {
      // Derived from state
      isEven: ({ state }) => state.count % 2 === 0,
      displayText: ({ state }) => state.count === 1 ? '1 item' : `${state.count} items`
    }
  </script>

Smart State, Dumb Templates

This strict separation is what makes Coralite so fast and AI-legible. The template remains a simple view layer, while the getters handle the business logic.

CORALITE-E201: Complex Template Expression

You cannot write expressions like {{ a + b }} or {{ count % 2 === 0 }} inside the template. Coralite will throw this error during the build. Move the logic into a getter and use a flat token like {{ isEven }}.

Batching and updateComplete

State mutations are batched within a microtask. If you need to wait for the DOM to finish updating, you can await the updateComplete promise provided in the client context.