Sunday, November 16, 2025
Performance Optimization with QuantaJS: A Complete Guide
Posted by

Performance Optimization with QuantaJS: A Complete Guide
Performance is crucial for smooth, responsive applications. QuantaJS 3.x tracks store dependencies and gives React components a few different subscription tools, so most performance work is about choosing the narrowest subscription that still keeps the component correct.
The examples below use store definitions created with defineStore, then resolve them through the 3.x React hooks.
Understanding QuantaJS Performance Characteristics
A store definition is cheap to keep at module scope. State lives in a container when the definition is resolved. In React:
useQuanta(definition)subscribes to the whole store.useQuantaValue(definition, selector)subscribes only to the selected value.useQuantaActions(definition)returns actions without subscribing to state.useLocalStore(definition)creates component-owned store state.
That gives you an explicit way to trade convenience for subscription precision.
1. Use Selectors for Fine-Grained Updates
When a component only needs one slice of a frequently changing store, subscribe to that slice.
❌ Broad subscription
function UserProfile() {
const user = useQuanta(useUserStore);
// Re-renders whenever the resolved store notifies.
return <div>{user.name}</div>;
}
✅ Fine-grained subscription
function UserProfile() {
const name = useQuantaValue(useUserStore, (state) => state.name);
return <div>{name}</div>;
}
Real-world example: todo list
const useTodosStore = defineStore('todos', {
state: () => ({
todos: [] as Array<{ id: string; text: string; done: boolean }>,
}),
});
function TodoList() {
const todos = useQuantaValue(useTodosStore, (state) => state.todos);
return (
<ul>
{todos.map((todo) => (
<TodoItem key={todo.id} todoId={todo.id} />
))}
</ul>
);
}
function TodoItem({ todoId }: { todoId: string }) {
const todo = useQuantaValue(
useTodosStore,
(state) => state.todos.find((item) => item.id === todoId),
);
return <li>{todo?.text}</li>;
}
The list watches the array, while each row selects only the item it displays.
2. Optimize Computed Values (Getters)
Put reusable derived state in getters instead of recomputing it in every component.
const useTodosStore = defineStore('todos', {
state: () => ({
todos: [] as Array<{ id: string; done: boolean }>,
filter: 'all' as 'all' | 'active' | 'completed',
}),
getters: {
filteredTodos: (state) => {
if (state.filter === 'active') {
return state.todos.filter((todo) => !todo.done);
}
if (state.filter === 'completed') {
return state.todos.filter((todo) => todo.done);
}
return state.todos;
},
completedCount: (state) => state.todos.filter((todo) => todo.done).length,
},
});
Then select the getter directly:
function TodoStats() {
const completedCount = useQuantaValue(
useTodosStore,
(state) => state.completedCount,
);
return <div>Completed: {completedCount}</div>;
}
This keeps the derivation next to the state model and avoids duplicating the same filter logic across components.
3. Optimize Watch Usage
Watch the smallest value that represents the side effect you care about.
function ThemeBridge() {
const settings = useQuanta(useSettingsStore);
useEffect(() => {
const stop = watch(
() => settings.preferences.theme,
(theme) => applyTheme(theme),
);
return stop;
}, [settings]);
return null;
}
Avoid watching a whole large object when one property is enough. If multiple values matter, return a small tuple or object and use an equality function appropriate for that value.
QuantaJS 3.x also lets watch take equals, so a shallow comparison can be used where reference equality would create unnecessary work.
4. Store Organization Strategies
Prefer domain stores over one application-wide mega-store.
const useUserStore = defineStore('user', {
state: () => ({ name: '', email: '' }),
});
const useCartStore = defineStore('cart', {
state: () => ({ items: [] as Array<{ id: string; price: number }> }),
getters: {
total: (state) => state.items.reduce((sum, item) => sum + item.price, 0),
},
});
const useSettingsStore = defineStore('settings', {
state: () => ({ theme: 'system' }),
});
A cart component can now subscribe only to the cart:
function CartSummary() {
const total = useQuantaValue(useCartStore, (state) => state.total);
return <div>Total: ${total}</div>;
}
The user and settings stores can change without waking this component.
5. Minimize State Updates
Group related writes inside one action when they belong to the same logical operation.
const useTodosStore = defineStore('todos', {
state: () => ({
todos: [] as Array<{ id: string; text: string }>,
filter: 'all',
}),
actions: {
addMultipleTodos(newTodos: Array<{ id: string; text: string }>) {
this.todos = [...this.todos, ...newTodos];
},
applyView(filter: string) {
this.filter = filter;
},
},
});
Dispatch without subscribing when a component only needs actions:
function ImportTodosButton({ todos }) {
const actions = useQuantaActions(useTodosStore);
return (
<button onClick={() => actions.addMultipleTodos(todos)}>
Import todos
</button>
);
}
Using useQuantaActions avoids a state subscription for dispatch-only UI.
6. Use Component-Scoped Stores When Appropriate
For state that belongs to one mounted component, define the store at module scope and resolve it with useLocalStore.
const useTodoFormStore = defineStore('todo-form', {
state: () => ({
text: '',
priority: 'medium' as 'low' | 'medium' | 'high',
}),
actions: {
setText(text: string) {
this.text = text;
},
},
});
function TodoForm() {
const form = useLocalStore(useTodoFormStore);
return (
<input
value={form.text}
onChange={(event) => form.setText(event.target.value)}
/>
);
}
Each <TodoForm /> gets its own container-backed store, and QuantaJS disposes it with the component.
Use local stores for form drafts, modal state, wizards, and other state that should not be shared globally.
7. Optimize Persistence
Persist only the state that must survive a reload.
const useAppStore = defineStore('app', {
state: () => ({
user: null as { id: string; name: string } | null,
settings: { theme: 'system' },
temporaryData: [] as string[],
}),
persist: {
adapter: new LocalStorageAdapter('app-store'),
include: ['user', 'settings'],
debounceMs: 500,
},
});
In 3.x, persistence options are typed from the store state. Keep the persisted slice small and serializable, and leave caches or short-lived request state out of it.
8. Performance Monitoring
Measure before optimizing. Browser DevTools and the QuantaJS logger are useful for finding repeated actions or unexpected subscriptions.
import { logger, LogLevel } from '@quantajs/core';
if (process.env.NODE_ENV === 'development') {
logger.configure({
level: LogLevel.DEBUG,
prefix: 'Performance',
});
}
For application-specific measurements, use the platform Performance API around the operation you are investigating instead of adding permanent timing logic to every action.
const started = performance.now();
await loadProducts();
console.debug('loadProducts', performance.now() - started);
9. React-Specific Optimizations
Choose the React hook by subscription intent.
function CartIcon() {
const itemCount = useQuantaValue(
useCartStore,
(state) => state.items.length,
);
return <span>{itemCount}</span>;
}
For a component that needs several related values, select them together and provide an equality function when appropriate:
import { shallow } from '@quantajs/core';
function AccountSummary() {
const summary = useQuantaValue(
useUserStore,
(state) => ({ name: state.name, email: state.email }),
{ equalityFn: shallow },
);
return (
<p>
{summary.name} — {summary.email}
</p>
);
}
For expensive computations that are truly component-specific rather than store-derived, normal React tools such as useMemo still apply.
10. Best Practices Summary
✅ Do
- Define stores once with
defineStore. - Use
useQuantaValuefor narrow state subscriptions. - Use
useQuantaActionsfor dispatch-only components. - Use getters for reusable derived state.
- Organize stores by domain.
- Use
useLocalStorefor component-owned state. - Persist only the state that needs to survive reloads.
- Measure before optimizing.
❌ Avoid
- Subscribing to an entire store when one value is enough.
- Repeating expensive derived calculations in several components.
- Watching large objects when a smaller source is available.
- Putting unrelated domains into one giant store.
- Persisting caches and temporary state.
- Creating local store definitions during render.
- Optimizing based on assumptions instead of measurements.
Real-World Example: Optimized E-Commerce Store
const useProductStore = defineStore('products', {
state: () => ({
products: [] as Array<{
id: string;
name: string;
category: string;
price: number;
}>,
filters: {
category: 'all',
priceRange: [0, 1000] as [number, number],
},
}),
getters: {
filteredProducts: (state) =>
state.products.filter((product) => {
const categoryMatches =
state.filters.category === 'all' ||
product.category === state.filters.category;
const priceMatches =
product.price >= state.filters.priceRange[0] &&
product.price <= state.filters.priceRange[1];
return categoryMatches && priceMatches;
}),
},
actions: {
updateFilters(filters: Partial<{ category: string; priceRange: [number, number] }>) {
Object.assign(this.filters, filters);
},
},
});
function ProductList() {
const products = useQuantaValue(
useProductStore,
(state) => state.filteredProducts,
);
return (
<div>
{products.map((product) => (
<ProductCard key={product.id} productId={product.id} />
))}
</div>
);
}
function ProductCard({ productId }: { productId: string }) {
const product = useQuantaValue(
useProductStore,
(state) => state.products.find((item) => item.id === productId),
);
return <div>{product?.name}</div>;
}
function ProductFilters() {
const filters = useQuantaValue(
useProductStore,
(state) => state.filters,
);
const actions = useQuantaActions(useProductStore);
return (
<button
onClick={() =>
actions.updateFilters({
...filters,
category: 'featured',
})
}
>
Show featured
</button>
);
}
Performance Checklist
Before deploying, check:
- Do narrow components use
useQuantaValueinstead of a broad subscription? - Are reusable derived calculations modeled as getters?
- Are stores organized by domain?
- Is persistence limited to necessary state?
- Are dispatch-only components using
useQuantaActions? - Is component-owned state using
useLocalStore? - Are watchers scoped to the smallest useful source?
- Have the suspected bottlenecks been measured?
Conclusion
Performance optimization in QuantaJS 3.x is mostly about subscription precision and keeping state boundaries clear.
Remember:
- Measure first.
- Subscribe narrowly.
- Keep definitions at module scope.
- Use local stores for local ownership.
- Keep persistence small.
- Optimize incrementally.
Happy optimizing! 🚀