QuantaJS Documentation

website·Indexed 29 days ago

https://www.quantajs.com

A framework-free state management library with official bindings for React, Vue, Svelte, Lit, and Astro. QuantaJS provides tools for reactive state, computed values, persistence, and server-side rendering (SSR) isolation. Key APIs include defineStore, createStore, reactive, and watch, with support for isolated store containers and dedicated DevTools for debugging.

Tokens
61.4K
Snippets
315
Records
359
Agent score
50%

What's inside QuantaJS

  1. Overview of QuantaJS State Management

    QuantaJS is a lightweight, framework-agnostic state management library inspired by the reactivity system of Vue.js and Pinia. It provides reactive state, computed values, and automatic dependency tracking. Key features include:

    • Framework Agnostic: Works in vanilla JS, React, Vue, Svelte, Lit, and Astro.
    • Automatic Reactivity: Tracks changes in objects, arrays, Maps, and Sets without manual reassignment.
    • Type Inference: State, getters, and actions are inferred end-to-end without requiring generics.
    • SSR Ready: Uses containers for per-request isolation and provides dehydrate()/hydrate() methods.
    • Built-in Async Handling: Actions automatically include pending, error, and abort() states, eliminating the need for manual loading flags.
  2. Use @quantajs/core for framework-agnostic state management

    The @quantajs/core package provides essential state management features that work with any JavaScript framework or vanilla JS. It includes tools for creating reactive stores, making objects reactive, creating derived cached values, and observing state changes.
    import { createStore, reactive, computed, watch } from '@quantajs/core';
    
    // Create a store
    const counterStore = createStore('counter', {
      state: () => ({ count: 0 }),
      getters: {
        doubleCount: (state) => state.count * 2
      },
      actions: {
        increment() { this.count++; }
      }
    });
    
    // Use reactive objects
    const user = reactive({ name: 'John', age: 30 });
    
    // Create computed values
    const userInfo = computed(() => `${user.name} is ${user.age} years old`);
    
    // Watch for changes
    watch(() => user.age, (newAge) => {
      console.log(`User age changed to ${newAge}`);
    });
  3. Use new framework bindings in Quanta 3.0

    Quanta 3.0 introduces official bindings for Vue, Svelte, and Lit, providing a consistent API across frameworks. The following hooks/controllers are available in these bindings: useQuanta, useQuantaValue, useQuantaActions, and useLocalStore.
  4. Understand and use Containers for store isolation

    A container is a set of store instances isolated from every other container. This prevents state leakage, which is critical in environments where a single process serves multiple users (like Node.js servers) or when running multiple tests. Containers enable request isolation under SSR, test isolation, and component-scoped stores.
    import { createContainer } from '@quantajs/core';
    
    const container = createContainer();
    const cart = useCartStore(container);
  5. Integrate QuantaJS with React using @quantajs/react

    The @quantajs/react package provides React-specific hooks and providers to integrate QuantaJS stores into a React application. Key exports include QuantaProvider for store injection and hooks like useStore and useQuantaStore for state access.
    import { QuantaProvider, useStore, useQuantaStore } from '@quantajs/react';
    
    function App() {
      return (
        <QuantaProvider stores={{ counter: counterStore }}>
          <Counter />
        </QuantaProvider>
      );
    }
    
    function Counter() {
      const store = useStore('counter');
      return (
        <div>
          <p>Count: {store.count}</p>
          <button onClick={() => store.increment()}>+</button>
        </div>
      );
    }
  6. Integrate QuantaJS state management with Lit

    The @quantajs/lit package provides reactive controllers that allow Lit elements to subscribe to QuantaJS stores. These controllers automatically handle the element lifecycle: subscribing when the element connects and unsubscribing when it disconnects. When the store state changes, the controller calls requestUpdate() to trigger a re-render of the element.
    npm install @quantajs/core @quantajs/lit
  7. QuantaJS Package Architecture

    QuantaJS is modular. Install only the packages required for your environment:

    • @quantajs/core: The framework-agnostic reactivity engine (stores, containers, computed, watchers, SSR hydration).
    • @quantajs/react: React bindings using useSyncExternalStore for concurrent-safe re-renders. Includes useQuanta, useQuantaValue, useQuantaActions, useLocalStore, useWatch, useComputed, and QuantaProvider.
    • @quantajs/vue: Vue composables including useQuanta, useQuantaValue, useQuantaActions, useLocalStore, and the createQuanta plugin for SSR.
    • @quantajs/svelte: Returns standard Svelte stores for $ subscriptions (compatible with Svelte 4, 5, and SvelteKit).
    • @quantajs/lit: Reactive controllers for web components (QuantaValueController, QuantaController, etc.).
    • @quantajs/astro: Integration providing a container per request and shared stores across React, Vue, and Svelte islands.
    • @quantajs/devtools: A developer overlay for real-time store inspection and action logging.
  8. Implement error handling and testing for QuantaJS stores

    To ensure stability and maintainability in QuantaJS state management, implement error handling within store actions using try-catch blocks, especially for asynchronous operations. For testing, leverage the framework-agnostic nature of the QuantaJS core package to perform unit tests on stores independently from React components.
  9. Handle reactive arrays and mutations

    Arrays created via reactive are fully reactive. This includes tracking for standard array mutations (e.g., .push(), .splice()) as well as updates to properties of objects contained within the array.
    import { reactive } from '@quantajs/core';
    
    const todos = reactive([
      { id: 1, text: 'Learn QuantaJS', done: false },
      { id: 2, text: 'Build an app', done: false },
    ]);
    
    todos.push({ id: 3, text: 'Deploy', done: false }); // Tracked
    todos[0].done = true; // Nested property change tracked
    todos.splice(1, 1); // Array method change tracked
  10. Implement custom serialization for complex data types

    For data types that cannot be handled by standard JSON (like Dates or custom classes), provide serialize and deserialize functions. Note that serialize receives the full envelope { data, version, timestamp, storeName }, and deserialize must return that same shape.
    persist: {
      adapter: new LocalStorageAdapter('complex-store'),
      serialize: (data) => {
        return JSON.stringify(data, (key, value) => {
          if (value instanceof Date) return { __type: 'Date', value: value.toISOString() };
          return value;
        });
      },
      deserialize: (data) => {
        return JSON.parse(data, (key, value) => {
          if (value && value.__type === 'Date') return new Date(value.value);
          return value;
        });
      }
    }
  11. Batch state updates to minimize re-renders

    Reduce the number of re-renders by batching multiple state changes into a single action rather than calling multiple sequential updates.
    const todoStore = createStore('todos', {
      state: () => ({ todos: [] }),
      actions: {
        // ✅ Good: Single update for multiple items
        addMultipleTodos(newTodos) {
          this.todos = [...this.todos, ...newTodos];
        }
      }
    });
    
    // Usage
    function addTodos() {
      // ✅ One re-render
      todoStore.addMultipleTodos([todo1, todo2, todo3]);
    }
  12. Implement QuantaJS in Server-Side Rendering (SSR)

    When using QuantaJS on the server, you must create a new container for every single request. The ambient container is shared across all requests in the process; failing to create a per-request container will result in data leaking between different visitors.