Quick Start
Let's jump into using QuantaJS with simple examples for both core and React usage.
Core Package Example
Here's how to create a reactive counter using createStore
from the core package:
import { createStore } from '@quantajs/core';
const counter = createStore('counter', {
state: () => ({ count: 0 }),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
},
});
// Access state
console.log(counter.count); // 0
console.log(counter.doubleCount); // 0
// Update state
counter.increment();
console.log(counter.count); // 1
console.log(counter.doubleCount); // 2
counter.decrement();
console.log(counter.count); // 0
console.log(counter.doubleCount); // 0
React Package Example
For React applications, use the React package with hooks and components:
import { createStore, QuantaProvider, useStore } from '@quantajs/react';
const counterStore = createStore('counter', {
state: () => ({ count: 0 }),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
},
});
function Counter() {
const store = useStore();
return (
<div>
<p>Count: {store.count}</p>
<p>Double: {store.doubleCount}</p>
<button onClick={() => store.increment()}>+</button>
<button onClick={() => store.decrement()}>-</button>
</div>
);
}
function App() {
return (
<QuantaProvider store={counterStore}>
<Counter />
</QuantaProvider>
);
}
What's Happening?
Core Package
createStore
creates a reactive store with a unique name, state function, getters, and actions- The
state
function returns the initial state object getters
are computed values that automatically update when dependencies change- Actions like
increment
anddecrement
modify the state directly usingthis
- All state changes trigger automatic reactivity
React Package
- Same store creation API as core package
QuantaProvider
wraps your app to provide the store to all child componentsuseStore
hook accesses the store from context and triggers re-renders when state changes- Components automatically re-render when store state updates
Performance Optimization
For React applications, you can use selectors to prevent unnecessary re-renders:
import { useQuantaStore } from '@quantajs/react';
function CounterDisplay() {
// Only re-render when count changes
const count = useQuantaStore(counterStore, store => store.count);
return <p>Count: {count}</p>;
}
Next Steps
Explore more features:
- Reactive State - Understanding reactivity
- Computed Values - Derived state
- Watching State - Side effects
- React Integration - React-specific features