- Home
- Skills
- Agents & Orchestration
- React 19 + MobX Guardrails
More screenshots
Works with the AI Agents you already use
React 19 + MobX Guardrails
Totals, prices, statuses and domain rounding come from the server.
$12
React 19 + MobX Guardrails
Example session with this skill installed
Our orders screen lags on every keystroke in the search box, and the total sometimes differs from the invoice by a few cents. Review the store and the component and fix them.
API contract: GET /api/orders returns { items: Order[], total: number }; the /ws/orders socket pushes { upserted: Order[], removedIds: string[], total: number }.
// src/pages/orders/OrdersPage.tsx
import { useEffect, useState } from 'react'
import { makeAutoObservable } from 'mobx'
import { observer } from 'mobx-react-lite'
export interface Order {
id: string
customer: string
qty: number
unitPrice: number
discountPct: number
}
class OrdersStore {
orders: Order[] = []
query = ''
loading = false
constructor() {
makeAutoObservable(this)
}
setQuery(query: string) {
this.query = query
}
async load() {
this.loading = true
const res = await fetch('/api/orders')
const body = (await res.json()) as { items: Order[]; total: number }
this.orders = body.items
this.loading = false
}
}
export const ordersStore = new OrdersStore()
export const OrdersPage = observer(() => {
const [visible, setVisible] = useState<Order[]>([])
useEffect(() => {
void ordersStore.load()
const ws = new WebSocket('/ws/orders')
ws.onmessage = (e: MessageEvent<string>) => {
const delta = JSON.parse(e.data) as { upserted: Order[]; removedIds: string[] }
ordersStore.orders = ordersStore.orders
.filter((o) => !delta.removedIds.includes(o.id))
.filter((o) => !delta.upserted.some((u) => u.id === o.id))
.concat(delta.upserted)
}
}, [])
useEffect(() => {
setVisible(ordersStore.orders.filter((o) => o.customer.includes(ordersStore.query)))
}, [ordersStore.orders, ordersStore.query])
const total = ordersStore.orders.reduce(
(sum, o) => sum + Math.round(o.qty * o.unitPrice * (1 - o.discountPct / 100) * 100) / 100,
0,
)
return (
<div>
<input value={ordersStore.query} onChange={(e) => ordersStore.setQuery(e.target.value)} />
{visible.map((o) => (
<div key={o.id}>
{o.customer}: {o.qty}
</div>
))}
<b>Total: {total.toFixed(2)}</b>
</div>
)
})
- Read your context and instructions
- Compiled the react 19
- Generated the UI component
Summary
7 findings in OrdersPage.tsx: 3 high, 3 medium, 1 low. The cent-level drift comes from the client re-deriving the total with per-line rounding instead of showing the backend's total. The lag comes from one broad observer plus a filtered list synced through an effect: 2 React commits per keystroke. The fix splits the file into an entity store, a feature store and small observer leaves; the total now comes from the backend only.
Findings
| # | Severity | Rule | Where | Problem | Fix |
|---|---|---|---|---|---|
| 1 | High | Domain/presentation boundary | total | The client re-derives qty × price × discount with per-line rounding, although the backend already sends total. Any difference in the backend's rounding shows up as cents. | Show total from the response and from every delta. |
| 2 | High | Rule 4: action context after await | load() | this.orders = … and this.loading = false run after await, outside an action. MobX logs "Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed". If fetch throws, loading stays true. | runInAction after await; try/finally for loading. |
| 3 | High | Rule 10 + Mirroring server state | WebSocket effect | No cleanup: every remount leaks a socket (StrictMode in dev keeps two live, both applying deltas). Each delta rebuilds the whole array outside an action. | subscribeOrderDeltas returns a disposer; applyDelta is one action keyed by id. |
| 4 | Medium | Rule 2: derive, don't sync | visible | The filtered list is copied into useState through useEffect, so every keystroke commits twice. | computed getter visible on the feature store. |
| 5 | Medium | Rule 1: narrow observers | OrdersPage | The whole page is one observer: typing re-renders the input, every row and the total. | observer leaves for the input, list, row and total; the page itself is not an observer. |
| 6 | Medium | State placement + Rule 5 | ordersStore | A module-level singleton mixes entity data (orders, loading) with feature UI state (query). | OrdersStore (entities, API injected) + OrderSearchStore (features), created once in app. |
| 7 | Low | No type exports from .tsx | export interface Order | ESLint (no-restricted-syntax) flags it at 6:8. | Move it to entities/order/model/models.ts. |
Four-condition test
| Value | Display-only | Pure function of delivered state | Deterministic | Not authoritative | Verdict |
|---|---|---|---|---|---|
visible (filter by customer) | ✅ | ✅ | ✅ | ✅ | Frontend, as a computed getter |
total | ✅ | ✅ | ✅ | ❌ users read it as the order total | Backend only; it also hits the explicit ban on domain rounding |
Code
src/entities/order/model/models.ts
// Shapes from the API contract. If you generate types from OpenAPI, import those instead.
export interface Order {
id: string
customer: string
qty: number
unitPrice: number
discountPct: number
}
export interface OrdersResponse {
items: Order[]
total: number
}
export interface OrdersDelta {
upserted: Order[]
removedIds: string[]
total: number
}
export interface OrdersApi {
fetchOrders(): Promise<OrdersResponse>
}
src/entities/order/model/OrdersStore.ts
import { makeAutoObservable, observable, runInAction } from 'mobx'
import type { Order, OrdersApi, OrdersDelta } from './models'
export class OrdersStore {
readonly byId = observable.map<string, Order>()
/** Authoritative total from the backend; null until the first response. */
total: number | null = null
loading = false
constructor(private readonly api: OrdersApi) {
makeAutoObservable<OrdersStore, 'api'>(this, { api: false })
}
get list(): Order[] {
return Array.from(this.byId.values())
}
async load(): Promise<void> {
this.loading = true
try {
const body = await this.api.fetchOrders()
runInAction(() => {
this.byId.replace(body.items.map((o) => [o.id, o]))
this.total = body.total
})
} finally {
runInAction(() => {
this.loading = false
})
}
}
/** One action per delta: observers never see a half-applied update. */
applyDelta(delta: OrdersDelta): void {
for (const id of delta.removedIds) this.byId.delete(id)
for (const order of delta.upserted) this.byId.set(order.id, order)
this.total = delta.total
}
}
src/entities/order/model/subscribeOrderDeltas.ts
import type { OrdersDelta } from './models'
import type { OrdersStore } from './OrdersStore'
/** Returns a disposer; the caller tears the socket down where it set it up. */
export function subscribeOrderDeltas(store: OrdersStore, url: string): () => void {
const ws = new WebSocket(url)
ws.onmessage = (e: MessageEvent<string>) => {
store.applyDelta(JSON.parse(e.data) as OrdersDelta)
}
return () => {
ws.close()
}
}
src/entities/order/api/httpOrdersApi.ts
import type { OrdersApi, OrdersResponse } from '../model/models'
export const httpOrdersApi: OrdersApi = {
async fetchOrders() {
const res = await fetch('/api/orders')
return (await res.json()) as OrdersResponse
},
}
src/entities/order/index.ts
export type { Order, OrdersApi, OrdersDelta, OrdersResponse } from './model/models'
export { OrdersStore } from './model/OrdersStore'
export { subscribeOrderDeltas } from './model/subscribeOrderDeltas'
export { httpOrdersApi } from './api/httpOrdersApi'
src/features/order-search/model/OrderSearchStore.ts
import { makeAutoObservable } from 'mobx'
import type { Order, OrdersStore } from '@/entities/order'
export class OrderSearchStore {
query = ''
constructor(private readonly orders: OrdersStore) {
makeAutoObservable<OrderSearchStore, 'orders'>(this, { orders: false })
}
setQuery(query: string): void {
this.query = query
}
/** Display-only filter over delivered fields: passes the four-condition test. */
get visible(): Order[] {
return this.orders.list.filter((o) => o.customer.includes(this.query))
}
}
src/features/order-search/ui/OrderSearchInput.tsx
import { observer } from 'mobx-react-lite'
import type { OrderSearchStore } from '../model/OrderSearchStore'
export const OrderSearchInput = observer(function OrderSearchInput({
search,
}: {
search: OrderSearchStore
}) {
return <input value={search.query} onChange={(e) => search.setQuery(e.target.value)} />
})
src/features/order-search/index.ts
export { OrderSearchStore } from './model/OrderSearchStore'
export { OrderSearchInput } from './ui/OrderSearchInput'
src/pages/orders/ui/OrdersPage.tsx
import { observer } from 'mobx-react-lite'
import { useEffect } from 'react'
import { subscribeOrderDeltas, type Order, type OrdersStore } from '@/entities/order'
import { OrderSearchInput, type OrderSearchStore } from '@/features/order-search'
const OrderRow = observer(function OrderRow({ order }: { order: Order }) {
return (
<div>
{order.customer}: {order.qty}
</div>
)
})
const OrderList = observer(function OrderList({ search }: { search: OrderSearchStore }) {
return search.visible.map((o) => <OrderRow key={o.id} order={o} />)
})
const OrdersTotal = observer(function OrdersTotal({ orders }: { orders: OrdersStore }) {
return <b>Total: {orders.total === null ? '…' : orders.total.toFixed(2)}</b>
})
interface OrdersPageProps {
orders: OrdersStore
search: OrderSearchStore
}
// Not an observer: the page itself reads no observables.
export function OrdersPage({ orders, search }: OrdersPageProps) {
useEffect(() => {
void orders.load()
return subscribeOrderDeltas(orders, '/ws/orders')
}, [orders])
return (
<div>
<OrderSearchInput search={search} />
<OrderList search={search} />
<OrdersTotal orders={orders} />
</div>
)
}
src/app/composition.ts
import { httpOrdersApi, OrdersStore } from '@/entities/order'
import { OrderSearchStore } from '@/features/order-search'
// Stores are created once, here, and passed down: no module-level singletons.
export const orders = new OrdersStore(httpOrdersApi)
export const search = new OrderSearchStore(orders)
Validation
| Check | Before | After |
|---|---|---|
tsc --noEmit (strict) | 0 errors | 0 errors |
ESLint with the skill's config, --max-warnings 0 | 1 error (no-restricted-syntax, 6:8) | 0 problems |
| MobX strict-mode warnings (runtime probe) | 1 | 0 |
| React commits per keystroke (vitest + jsdom, 1000 orders) | 2 | 1 |
A delta that removes a, updates b and adds c reaches observers in one step, a:1,b:2 total=30 → b:5,c:1 total=42, with no intermediate state.
Next steps
Snapshot/delta race. If a delta can arrive before GET /api/orders returns, load() overwrites it with an older snapshot. The fix needs a version or sequence number in the contract: ask the backend team rather than reconciling on the client.
Reconnect. On reconnect, call orders.load() for a fresh snapshot and show the connection status from an app-level store.
- CI. Merge
references/eslint-limits.mdinto your ESLint config and runeslint . --max-warnings 0.
Pin the seam. Add one component test that types into the search and checks the rows and the total, so the stores and the UI stay wired together.
OrdersPage.tsx
TSX · React component
Example file from a real run - the skill writes it into your workspace.
Connects securely to your tools. The creator never sees your data.
About this skill
Stop your agent from putting business logic in the browser
AI coding agents write React + MobX that works on the first try and drifts by the tenth change: totals recomputed on the client that no longer match the server, one giant observer that re-renders the whole page, useEffect used to sync derived state, observables written after await outside an action, WebSocket subscriptions that are never closed, 600-line components split by line count.
This skill gives your agent the rules a senior frontend lead enforces in review, and it applies them every time the agent touches a component, a store, server data or performance, not only when you remember to ask.
What it does
- Backend-authoritative boundary. A four-condition test decides whether a value may be computed in the browser: display-only, a pure function of delivered state, deterministic, not authoritative. Totals, prices, statuses and domain rounding come from the server. When in doubt, the agent stops and asks you instead of guessing.
- State placement. Local state, feature store, entity store or app level, with no catch-all root store.
- MobX correctness. Narrow
observerleaves,computedgetters instead of effect-synced state,runInAction/flowafterawait, a disposer for every reaction, socket and timer, one action per server delta keyed by id. - Layer model.
app → pages → widgets → features → entities → shared: dependencies point down only, imports go throughindex.ts. If you have your own architecture document, it wins. - Size limits with a reason. 80 code lines per function, 300 per file, complexity 12, plus a splitting order (layer → state → pure function → markup), so the agent fixes the design instead of slicing JSX.
- React 19 specifics. When
startTransitionanduseDeferredValuehelp, and when they are noise. - Review checklist. The agent runs it against your diff.
What's in the ZIP
SKILL.md: the rules, written for agents (about 250 lines).references/eslint-limits.md: a ready-to-paste ESLint flat config for the size limits, the "no type exports from.tsx" rule and test overrides. Tested on ESLint 10.7 with typescript-eslint 8.64.
Who it's for
Teams building data-heavy React 19 + MobX apps where the server is the source of truth: back-office tools, ERP, scheduling, trading and monitoring dashboards fed by REST and WebSockets.
Where it comes from
The rules come from a production React 19 + MobX scheduling application built with AI agents under strict code review, with all project-specific details removed.
Frontend must be presentational only. Does not support local-first domain logic. Strict 80/300/12 line limits applied. Requires MobX for state management.
How to use
- 1
Connect your agent to the Agensi MCP
Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup
- 2
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before any payment.
Reviews
No reviews yet
Be one of the first to try it. Every listed skill goes through the trust checks below.
Security scanned
Checked by our 8-point scan before listing
Fresh listing
Recently published to Agensi
Money-back guarantee
Doesn't do what its page promises? You get your money back.
Trust & safety
Security scan
Security scan passed 20 days ago
Permissions
File Scopes
The skill reads and edits React and MobX source files when you ask it to write, refactor or review them. Shell access is used only to run your own linter and type checker to measure the size limits. It makes no network calls, needs no accounts and stores nothing outside your project.