### Create a Simple Reactive Anchor Component Source: https://github.com/beerush-id/anchor/blob/main/docs/react/getting-started.md Demonstrates creating a basic Anchor component using `setup()`, `mutable()`, and `render()`. The `setup` function defines the component's state (`mutable`) and logic, while `render` defines the reactive UI. The example shows a counter that increments on button click. ```tsx import { setup, mutable, render } from '@anchorlib/react'; // ━━━ COMPONENT (Logic Layer) ━━━ export const Counter = setup(() => { const state = mutable({ count: 0 }); // ━━━ VIEW (Presentation Layer) ━━━ return render(() => ( )); }); ``` -------------------------------- ### Install Anchor React Library Source: https://github.com/beerush-id/anchor/blob/main/docs/react/getting-started.md Installs the Anchor React library using npm. This is the first step to integrating Anchor into your React project. ```bash npm install @anchorlib/react ``` -------------------------------- ### Full Migration to setup() with TodoApp Example Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-knowledge-base.md Demonstrates converting a React component to use Anchor.js's setup() function for complete stability. It includes mutable state for form input and todos, and uses snippets for reusable UI parts like the TodoForm and TodoList. This pattern enhances stability by managing state and logic within a stable function scope. ```tsx export const TodoApp = setup(() => { const formState = mutable({ text: '' }); const todos = mutable([]); const handleSubmit = () => { todos.push({ text: formState.text }); formState.text = ''; }; const TodoForm = snippet(() => ( formState.text = e.target.value} /> )); const TodoList = snippet(() => ( )); return (
); }); ``` -------------------------------- ### Anchor Component and View Example Source: https://github.com/beerush-id/anchor/blob/main/docs/react/index.md Demonstrates how to set up a component with a logic layer and a reactive presentation layer using Anchor. The logic layer runs once, ensuring stable closures, while the presentation layer (snippets and static layout) updates only when dependent state changes. This example uses `setup`, `mutable`, `snippet`, and `render` from '@anchorlib/react'. ```tsx import { setup, mutable, snippet, render } from '@anchorlib/react'; // ━━━ COMPONENT (Logic Layer) ━━━ export const Counter = setup(() => { // Runs once. Logic is stable, no dependency arrays needed. const state = mutable({ count: 0 }); const increment = () => state.count++; // ━━━ VIEW (Presentation Layer) ━━━ // Reactive Snippet - only re-runs when state.count changes const Count = snippet(() =>

{state.count}

, 'Count'); // Static Layout - runs once, never re-renders return ( <> ); }, 'Counter'); ``` -------------------------------- ### TypeScript Component Setup Examples Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-knowledge-base.md Demonstrates various ways to define components using TypeScript, including basic components with props, components with two-way binding, and using `template` and `snippet` for reusable UI elements. It also shows how to define mutable state and node references with types. ```tsx // Component with props interface Props { value: number; onChange?: (val: number) => void; } export const Counter = setup((props) => { // Can destructure in render() return render(({ value }) => (
{value}
)); }); // Component with two-way binding interface TextInputProps { value: Bindable; // Two-way binding placeholder?: string; } export const TextInput = setup((props) => { const handleChange = (e) => props.value = e.target.value; return render(() => ( )); }); // Template with props const Button = template<{ variant: 'primary' | 'secondary' }> ( ({ variant }) => )); const TodoList = snippet(() => (
    {todos.map(todo => )}
)); return (
); }); // STEP 3: External Component Definition // Pure views are defined outside to maximize reusability. const TodoItem = template(({ todo }) => (
  • todo.completed = !todo.completed} /> {todo.text}
  • )); ``` -------------------------------- ### State-Driven vs. Logic-Driven Component Setup (React) Source: https://github.com/beerush-id/anchor/blob/main/docs/react/best-practices.md Demonstrates the difference between recreating functions on every render in a state-driven approach (requiring useCallback) and creating functions once within setup() in a logic-driven approach, which always references the current state. ```tsx // ❌ Functions recreated on every render const [count, setCount] = useState(0); // This function is recreated on every render const increment = () => setCount(count + 1); // Need useCallback to stabilize const stableIncrement = useCallback(() => { setCount(c => c + 1); }, []); // Empty deps, but uses updater function ``` ```tsx // ✅ Function created once, always current export const Counter = setup(() => { const state = mutable({ count: 0 }); // Created once, always references current state.count const increment = () => state.count++; return render(() => ( )); }); ``` -------------------------------- ### Simple Component Rendering with render() Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-knowledge-base.md An example of a simple Anchor.js component using setup() and render(). This is suitable for components with minimal reactive state where full re-renders do not impact performance. ```tsx export const SimpleCard = setup(() => { const state = mutable({ title: 'Card', count: 0 }); // Simple component - just use render() return render(() => (

    {state.title}

    Count: {state.count}

    )); }); ``` -------------------------------- ### Component Logic Layer with setup() Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-knowledge-base.md Demonstrates the core logic layer of a component using the `setup()` function. It handles state, logic, effects, and lifecycle hooks. Runs once on mount. ```tsx export const UserCard = setup((props) => { // State const state = mutable({ expanded: false }); // Logic const toggle = () => state.expanded = !state.expanded; // Effects effect(() => console.log('Expanded:', state.expanded)); // Lifecycle onMount(() => console.log('Mounted')); onCleanup(() => console.log('Unmounted')); // Return View return render(() =>
    ...
    ); }, 'UserCard'); ``` -------------------------------- ### Reactive Props Handling in setup() Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-knowledge-base.md Illustrates correct and incorrect ways to handle reactive props within the `setup()` function. Emphasizes avoiding prop destructuring to maintain reactivity. ```tsx // ❌ Wrong const { name } = props; // Captures initial value only // ✅ Correct effect(() => console.log(props.name)); // Tracks changes ``` -------------------------------- ### Anchor Reactive Props Example Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-knowledge-base.md Shows how Anchor's props are reactive proxies, unlike React's plain objects. This example demonstrates defining props with `setup` and using them in the rendered view. ```tsx // Anchor props are reactive proxies export const Card = setup((props) => { return render(() => (
    {props.children}
    )); }); ``` -------------------------------- ### Display Data Based on Reactive Status in UI Components Source: https://github.com/beerush-id/anchor/blob/main/docs/react/state/async-handling.md Shows a React component example using setup, query, and reactive status. The UI conditionally renders loading indicators, error messages, or data based on the 'user.status'. ```tsx import { setup, query } from '@anchorlib/react'; export const UserProfile = setup(() => { const user = query(async (signal) => { const res = await fetch('/api/user', { signal }); return res.json(); }); return (
    {user.status === 'pending' &&

    Loading...

    } {user.status === 'error' &&

    Error: {user.error?.message}

    } {user.status === 'success' &&

    Hello, {user.data.name}!

    }
    ); }); ``` -------------------------------- ### Props Handling with $omit() in setup() Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-knowledge-base.md Shows how to manage props within the `setup()` function using `$omit()` to exclude specific keys, preventing errors and ensuring reactivity when passing props to child elements. ```tsx export const Card = setup((props) => { const divProps = props.$omit(['variant']); // Exclude specific keys return render(() => (
    {props.children}
    )); }); ``` -------------------------------- ### Build Universal Anchor Components (RSC, SSR, CSR) Source: https://github.com/beerush-id/anchor/blob/main/docs/react/getting-started.md Demonstrates building a universal Anchor component (`UserProfile`) that supports React Server Components (RSC), Server-Side Rendering (SSR), and Client-Side Rendering (CSR). It uses `setup`, `mutable`, `render`, `onMount`, and `callback` to handle state, fetching, lifecycle, and interactions across different rendering environments. ```tsx import { setup, mutable, render, onMount, callback } from '@anchorlib/react'; type User = { id: number; name: string }; type UserState = { user: User | null; loading: boolean; error: string | null; }; type Props = { id?: number; user?: User; }; export const UserProfile = setup(({ id, user }: Props) => { // 1. State // If 'user' is provided (RSC), we start loaded! const state = mutable({ user: user || null, loading: !user, error: null, }); // 2. Logic const getUser = () => { if (!id) return; // Can't fetch without ID state.loading = true; state.error = null; fetch(`/api/users/${id}`) .then(res => res.json()) .then(data => { state.user = data; state.loading = false; }) .catch(err => { state.error = err.message; state.loading = false; }); }; // 3. Lifecycle // Only fetch on mount if we don't have a user yet. onMount(() => { if (!state.user && id) { getUser(); } }); // 4. Snippets // Extract content to a snippet so updates to 'user.name' // don't re-run the main render loop (checking loading/error). const Content = snippet(() => (

    {state.user?.name}

    {/* Only show refresh if we have an ID to refetch with */} {id && }
    )); // 5. Component View // Main view only re-renders when loading/error state changes. return render(() => { if (state.loading) return
    Loading...
    ; if (state.error) return
    {state.error}
    ; return ; }); }); ``` -------------------------------- ### Component Naming with Setup, Render, Template, and Snippet Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-knowledge-base.md Demonstrates how to name components, templates, and snippets using the setup, render, template, and snippet functions from the Anchor library. Proper naming enhances visibility in React DevTools. The second argument to these functions specifies the name. ```tsx // Component with named view const Tab = setup(() => { return render(() =>
    Tab
    , 'Tab'); }, 'Tab'); // Template const TodoItem = template(({ todo }) =>
  • {todo.text}
  • , 'TodoItem'); // Snippet const Header = snippet(() =>

    Title

    , 'Header'); ``` -------------------------------- ### Parallel Query Execution for Independent Data in TypeScript Source: https://github.com/beerush-id/anchor/blob/main/docs/react/state/async-handling.md Demonstrates initiating multiple independent queries simultaneously using `query()` within a `mutable` setup. This approach avoids request waterfalls by starting all queries at once. A computed property `isReady` checks if all parallel queries have succeeded. Requires `setup`, `mutable`, `query`, and `render` functions. ```typescript export const Dashboard = setup(() => { const store = mutable({ // All three start immediately in parallel user: query(fetchUser), stats: query(fetchStats), notifications: query(fetchNotifications), get isReady() { return this.user.status === 'success' && this.stats.status === 'success' && this.notifications.status === 'success'; } }); return render(() => (
    {store.isReady ? : }
    )); }); ``` -------------------------------- ### React Integration with @anchorlib/react Source: https://context7.com/beerush-id/anchor/llms.txt Shows how to integrate Anchor with React using compiler-mode signals. This section covers using `mutable()`, `derived()`, `setup()`, and `template()` for building reactive UI components. It also mentions importing client-side setup and accessing core functions and storage. ```typescript import '@anchorlib/react/client'; // Must import in client components import { mutable, derived } from '@anchorlib/react'; import { setup, template } from '@anchorlib/react'; import { z } from 'zod'; // Using setup() and template() pattern const TodoApp = setup(() => { const todos = mutable([ { id: 1, text: 'Learn Anchor', done: false }, { id: 2, text: 'Build app', done: false } ]); const addTodo = (text: string) => { // Direct mutation triggers re-render todos.push({ id: Date.now(), text, done: false }); }; const toggleTodo = (index: number) => { todos[index].done = !todos[index].done; }; // Fine-grained reactive view const TodoList = template(() => ( <> {todos.map((todo, i) => (
    toggleTodo(i)} /> {todo.text}
    ))} )); return (
    ); }); // With derived computed value const Counter = setup(() => { const count = mutable(0); const doubled = derived(() => count.value * 2); const CountView = template(() => ( <>

    Count: {count.value}

    Doubled: {doubled.value}

    )); return (
    ); }); // Access core functions import { anchor, subscribe } from '@anchorlib/react/core'; // Access storage functions import { MemoryStorage, SessionStorage } from '@anchorlib/react/storage'; ``` -------------------------------- ### Anchor Core Imports and Setup Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-system-prompt.md Provides a quick reference for importing essential functions and types from the `@anchorlib/react` package, including state management, component rendering, reactivity utilities, and storage options. It also notes the requirement to initialize the client. ```tsx import { // State mutable, immutable, writable, derived, // Component & Views setup, render, template, snippet, // Reactivity effect, untrack, snapshot, subscribe, // Lifecycle onMount, onCleanup, // Binding $bind, $use, type Bindable, // Async Handling query, // Utils nodeRef, stringify, form, undoable } from '@anchorlib/react'; // Storage import { persistent, session } from '@anchorlib/react/storage'; // Initialize client (required) import '@anchorlib/react/client'; ``` -------------------------------- ### State Persistence with persistent and session in React Storage Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-system-prompt.md Demonstrates how to make application state reactive and automatically sync with browser storage using `@anchorlib/react/storage`. It shows examples of `persistent()` for localStorage and `session()` for sessionStorage, explaining their use cases and how changes automatically trigger UI updates. Includes an example of using `effect` to log changes. ```tsx import { persistent, session } from '@anchorlib/react/storage'; // Persistent (localStorage) - survives browser restart const settings = persistent('app-settings', { theme: 'dark', language: 'en' }); settings.theme = 'light'; // Auto-saves to localStorage // Session (sessionStorage) - cleared on tab close const formDraft = session('post-draft', { title: '', content: '' }); formDraft.title = 'New Post'; // Auto-saves to sessionStorage // Both are reactive - changes trigger UI updates effect(() => { console.log('Theme changed:', settings.theme); }); ``` -------------------------------- ### Define Reactive Counter Component with Anchor Source: https://github.com/beerush-id/anchor/blob/main/docs/react/component/index.md This example demonstrates how to create a basic reactive counter component using Anchor's `setup`, `render`, and `mutable` functions. It defines the component's state and logic in the 'Component' layer and the UI rendering in the 'View' layer, ensuring logic runs once and the UI updates reactively. ```tsx import { setup, render, mutable } from '@anchorlib/react'; // ━━━ COMPONENT (Logic Layer) ━━━ export const Counter = setup((props) => { // State and logic - runs once const state = mutable({ count: 0 }); const increment = () => { state.count++; }; // ━━━ VIEW (Presentation Layer) ━━━ // Runs reactively when state.count changes return render(() => ( )); }, 'Counter'); ``` -------------------------------- ### Initialize Anchor Client for React Hooks Source: https://github.com/beerush-id/anchor/blob/main/docs/react/getting-started.md Initializes the Anchor client by importing '@anchorlib/react/client'. This crucial step binds Anchor's reactive system to React's hooks, enabling reactivity in the browser. It should be done before any components are rendered. ```tsx // main.tsx or app/layout.tsx import '@anchorlib/react/client'; // 👈 Binds React hooks import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; ReactDOM.createRoot(document.getElementById('root')!).render(); ``` -------------------------------- ### Basic Component Setup in Anchor Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-system-prompt.md Defines a basic Anchor component named 'Counter'. It utilizes `setup()` for the logic layer, `mutable()` for state management, and `render()` for the reactive view layer. The component displays a count and increments it on button click. ```tsx export const Counter = setup(() => { // Logic Layer - runs once const state = mutable({ count: 0 }); // View Layer - reactive return render(() => ( ), 'Counter'); }, 'Counter'); ``` -------------------------------- ### Dynamic Dependency Tracking Example in Anchor (tsx) Source: https://github.com/beerush-id/anchor/blob/main/docs/react/best-practices.md Demonstrates Anchor's dynamic dependency tracking within an effect. The effect only tracks 'state.details' when 'state.showDetails' is true, showcasing how dependencies adapt to execution paths. ```tsx effect(() => { if (state.showDetails) { // This property is ONLY tracked when showDetails is true console.log(state.details); } }); // When showDetails is false: // - Changing state.details does NOT trigger the effect // When showDetails becomes true: // - Effect re-runs, reads details, starts tracking it // - Now changing state.details WILL trigger the effect ``` -------------------------------- ### Automatic Query Cancellation with start() and effect() in TypeScript Source: https://github.com/beerush-id/anchor/blob/main/docs/react/state/async-handling.md Demonstrates how calling `start()` on a pending query automatically cancels the previous request. It uses `effect()` to re-fetch when dependencies change, providing a search-as-you-type experience with built-in cancellation. Dependencies include a mutable term and the `query` and `effect` functions. ```typescript const term = mutable(''); const search = query( async (signal) => { const res = await fetch(`/api/search?q=${term.value}`, { signal }); return res.json(); }, [], { deferred: true } ); // Automatically re-fetch when term changes effect(() => { if (term.value) { search.start(); // Cancels previous request automatically } }); // Just update the term, effect handles the rest term.value = 'new query'; ``` -------------------------------- ### POST and PUT Request Methods with Fetch State Source: https://github.com/beerush-id/anchor/blob/main/docs/react/state/async-handling.md Demonstrates how to configure `fetchState()` for HTTP methods other than GET, specifically POST and PUT. It shows how to specify the `method` and include a `body` for requests that modify data on the server. ```typescript // POST request with body const createUser = fetchState( null, { url: '/api/users', method: 'POST', body: { name: 'John', email: 'john@example.com' } } ); // PUT request const updateUser = fetchState( null, { url: '/api/users/123', method: 'PUT', body: { name: 'Jane' } } ); ``` -------------------------------- ### Basic Fetch State Initialization in TypeScript Source: https://github.com/beerush-id/anchor/blob/main/docs/react/state/async-handling.md Shows the basic usage of `fetchState()` from Anchor for managing HTTP requests. It initializes a reactive state for a GET request to '/api/user', providing default empty values for the expected response structure. ```typescript import { fetchState } from '@anchorlib/react'; const userState = fetchState( { name: '', email: '' }, { url: '/api/user' } ); ``` -------------------------------- ### RSC: Render Static HTML with Anchor Source: https://github.com/beerush-id/anchor/blob/main/docs/react/getting-started.md Demonstrates using Anchor as a Server Component (RSC). It passes only data, resulting in static HTML output with no client-side JavaScript for interactivity. ```tsx // page.tsx (Server Component) import { db } from './db'; import { UserProfile } from './UserProfile'; export default async function Page({ params }) { const user = await db.user.find(params.id); // Renders Static HTML. Zero JS. return ; } ``` -------------------------------- ### CSR: Fetch Data and Handle Loading with Anchor Source: https://github.com/beerush-id/anchor/blob/main/docs/react/getting-started.md Illustrates using Anchor as a Client Component (CSR). Only the ID is passed, allowing the component to manage loading states and data fetching entirely within the browser. ```tsx // App.tsx (Client Component) import { UserProfile } from './UserProfile'; export default function App() { // Shows "Loading..." then fetches data return ; } ``` -------------------------------- ### SSR: Render HTML and Hydrate with Anchor Source: https://github.com/beerush-id/anchor/blob/main/docs/react/getting-started.md Shows how to use Anchor with Server-Side Rendering (SSR). Both data and an ID are passed, generating HTML on the server and enabling client-side hydration for interactive features like a refresh button. ```tsx // clients/index.ts 'use client'; export { UserProfile } from '../components/UserProfile'; ``` ```tsx // page.tsx (SSR Route) import { db } from './db'; import { UserProfile } from './clients'; export default async function Page({ params }) { const user = await db.user.find(params.id); // Renders HTML + Hydrates. Interactive. return ; } ``` -------------------------------- ### Static Layout with Reactive Templates Source: https://github.com/beerush-id/anchor/blob/main/docs/react/component/view.md Creates a static layout structure using `setup` that only renders once. Embeds reactive `template` components within the static structure to allow specific parts to update independently based on state changes. This optimizes performance by preventing unnecessary re-renders of static elements. ```tsx export const Dashboard = setup(() => { const state = mutable({ title: 'Dashboard', data: [] }); // Templates const Header = template(() =>
    {state.title}
    , 'Header'); const Content = template(() =>
    {state.data}
    , 'Content'); // Static Layout (runs once) return (
    {/* Updates when state.title changes */}
    Static Sidebar
    {/* Updates when state.data changes */}
    ); }, 'Dashboard'); ``` -------------------------------- ### Memoize Unoptimized Third-Party React Components Source: https://github.com/beerush-id/anchor/blob/main/docs/react/migration-guide.md Provides an example of how to wrap an unoptimized third-party React component (like Shadcn/UI's Badge) with `React.memo` to improve performance within Anchor. This is useful if the component library does not include internal memoization. ```tsx import { memo } from 'react'; import { Badge as ShadcnBadge } from '@/components/ui/badge'; // Wrap if the library component isn't already memoized const Badge = memo(ShadcnBadge); ``` -------------------------------- ### Make Dynamic Fetch Requests with fetchState Source: https://github.com/beerush-id/anchor/blob/main/docs/react/state/async-handling.md Demonstrates how to use the fetchState function to make dynamic HTTP requests. It shows basic usage and how to override default fetch options like URL and headers for subsequent requests. ```typescript const userState = fetchState( null, { url: '/api/user', deferred: true } ); // Fetch with custom options userState.fetch({ url: '/api/user/123', headers: { 'Authorization': 'Bearer token' } }); ``` -------------------------------- ### Integrate Anchor Components into React Components Source: https://github.com/beerush-id/anchor/blob/main/docs/react/migration-guide.md Shows how to embed Anchor components (created with `setup` and `render`) directly within a standard React component (`ReactApp`). The Anchor component maintains its stable scope while receiving props like `onIncrement` from the React parent. ```tsx import { useState } from 'react'; import { setup, render, mutable } from '@anchorlib/react'; // Stable component with internal state const Counter = setup<{ onIncrement?: () => void }>((props) => { const state = mutable({ count: 0 }); const increment = () => { state.count++; props.onIncrement?.(); }; return render(() => ( )); }); // React component const ReactApp = () => { const [total, setTotal] = useState(0); return (

    Total clicks: {total}

    setTotal(t => t + 1)} />
    ); }; ``` -------------------------------- ### Implement Selective Rendering with Anchor Snippets Source: https://github.com/beerush-id/anchor/blob/main/docs/react/getting-started.md Illustrates using `snippet()` in Anchor to split UI logic within a component without prop drilling. Snippets are context-aware views that can access component state directly, improving cohesion and performance by allowing independent updates. ```tsx import { setup, mutable, snippet } from '@anchorlib/react'; // ━━━ COMPONENT (Logic Layer) ━━━ export const UserCard = setup(() => { const user = mutable({ name: 'John Doe', role: 'Admin' }); // ━━━ SNIPPET (Context-aware View) ━━━ const Header = snippet(() => (

    {user.name}

    )); // ━━━ SNIPPET (Context-aware View) ━━━ const Body = snippet(() => (

    Role: {user.role}

    )); // ━━━ STATIC JSX (Static Presentation Layer) ━━━ return (
    ); }); ``` -------------------------------- ### Create Anchor Component with Logic and View Source: https://github.com/beerush-id/anchor/blob/main/docs/react/component/setup.md Demonstrates the creation of an Anchor Component using the `setup` function. It initializes mutable state, defines a logic function (`increment`), and returns a reactive view using `render` for a button that displays and updates a counter. ```tsx import { setup, render, mutable } from '@anchorlib/react'; // ━━━ COMPONENT (Logic Layer) ━━━ export const Counter = setup((props) => { // State and logic const state = mutable({ count: 0 }); const increment = () => state.count++; // ━━━ VIEW (Presentation Layer) ━━━ return render(() => ( )); }, 'Counter'); ``` -------------------------------- ### Reusable List Rendering with Anchor Components Source: https://github.com/beerush-id/anchor/blob/main/docs/react/best-practices.md Demonstrates how to create reusable, self-contained list items and manage dynamic lists using Anchor's `template`, `setup`, `mutable`, and `snippet` functions. It showcases encapsulated state management and event handling within list items. ```tsx const TodoItem = template<{ todo: Todo }>(({ todo }) => (
  • todo.done = !todo.done} /> {todo.text}
  • )); export const TodoList = setup(() => { const state = mutable({ todos: [], remove(todo) { const index = this.todos.indexOf(todo); if (index !== -1) { this.todos.splice(index, 1); } } }); const TodoItem = snippet<{ todo: Todo }>(({ todo }) => (
  • {todo.text}
  • )); return render(() => (
      {state.todos.map(todo => ( ))}
    )); }); ``` -------------------------------- ### State Serialization with stringify in Core Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-system-prompt.md Illustrates the correct way to serialize state for storage or transmission using `@anchorlib/core`'s `stringify()` function. It highlights the benefit of `stringify()` over `JSON.stringify()` by avoiding unnecessary subscriptions to state properties. Provides an example of serializing state and saving it to localStorage. ```tsx import { stringify } from '@anchorlib/core'; // ❌ Don't use JSON.stringify() - subscribes to all properties // const json = JSON.stringify(state); // ✅ Use stringify() - reads without subscribing const json = stringify(state); localStorage.setItem('app-state', stringify(state)); ``` -------------------------------- ### Deferred Data Fetching with Component Structure in React Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-system-prompt.md Sets up a React component to fetch user data and posts using deferred queries. It manages loading and error states and renders UI snippets for user information and posts. Includes setup, data fetching, mount/cleanup logic, and rendering. ```tsx export const UserProfile = setup<{ userId: number }>((props) => { // Deferred queries with initial data const user = query( async (signal) => { const res = await fetch(`/api/users/${props.userId}`, { signal }); return res.json(); }, { name: '', email: '' }, { deferred: true } ); const posts = query( async (signal) => { const res = await fetch(`/api/posts?user=${props.userId}`, { signal }); return res.json(); }, [], { deferred: true } ); // Fetch on mount onMount(() => { user.start(); posts.start(); }); // Cleanup on unmount onCleanup(() => { user.abort(); posts.abort(); }); // Snippets for granular updates const UserInfo = snippet(() => (

    {user.data.name}

    {user.data.email}

    ), 'UserInfo'); const PostsList = snippet(() => (

    Posts ({posts.data.length})

    {posts.data.map(post =>
    {post.title}
    )}
    ), 'PostsList'); // Use render() for reactive status checks return render(() => (
    {user.status === 'pending' &&

    Loading user...

    } {user.status === 'error' &&

    Error: {user.error?.message}

    } {user.status === 'success' && ( <> {posts.status === 'pending' &&

    Loading posts...

    } {posts.status === 'success' && } )}
    ), 'UserProfile'); }, 'UserProfile'); ``` -------------------------------- ### Deferred Query Execution with Anchor Source: https://github.com/beerush-id/anchor/blob/main/docs/react/state/async-handling.md Shows how to use the `deferred` option with the `query()` function to prevent immediate execution. The query is only started manually later using the `start()` method, providing control over when the asynchronous operation is triggered. ```typescript const userQuery = query( async (signal) => { const response = await fetch('/api/user', { signal }); return response.json(); }, undefined, { deferred: true } ); // Later, when ready userQuery.start(); ``` -------------------------------- ### Reactive HTTP Requests with fetchState() and streamState() Source: https://context7.com/beerush-id/anchor/llms.txt Demonstrates how to create reactive fetch states for HTTP requests using `fetchState` and `streamState` from `@anchorlib/core`. It covers GET and POST requests, deferred fetching, streaming responses, and converting states to promises. Built-in loading and error states are automatically managed. ```typescript import { fetchState, streamState, FetchStatus } from '@anchorlib/core'; import { subscribe } from '@anchorlib/core'; // GET request const userState = fetchState( { id: 0, name: '', email: '' }, { url: 'https://api.example.com/user/123', method: 'GET' } ); subscribe(userState, (state) => { console.log('Status:', state.status); if (state.status === FetchStatus.Success) { console.log('User loaded:', state.data); } else if (state.status === FetchStatus.Error) { console.error('Failed:', state.error); } }); // POST with body const createUserState = fetchState( { success: false, userId: null }, { url: 'https://api.example.com/users', method: 'POST', body: { name: 'Alice', email: 'alice@example.com' }, headers: { 'Content-Type': 'application/json' } } ); // Deferred fetch (manual trigger) const lazyFetch = fetchState( [], { url: 'https://api.example.com/items', deferred: true } ); lazyFetch.fetch(); // Trigger manually lazyFetch.abort(); // Cancel request // Stream responses const chatState = streamState( { messages: '' }, { url: 'https://api.example.com/chat/stream', method: 'POST', body: { prompt: 'Hello AI' }, transform: (current, chunk) => { // Accumulate chunks return { messages: current.messages + chunk.messages }; } } ); // Convert to promise const result = await fetchState.promise(userState); console.log('Final data:', result.data); ``` -------------------------------- ### Two-Way Binding Usage Examples in React (Anchor) Source: https://github.com/beerush-id/anchor/blob/main/docs/react/component/binding.md Provides examples of how to use a component typed for two-way binding in Anchor. It shows usage with one-way pass-by-value, pass-by-reference, and two-way binding using `$bind()`. ```tsx // ✅ One-way pass-by-value render(() => ) // ✅ One-way pass-by-reference // ✅ Two-way binding // ✅ Two-way binding + imperative handling ``` -------------------------------- ### Re-fetching Data with Anchor Queries Source: https://github.com/beerush-id/anchor/blob/main/docs/react/state/async-handling.md Explains how to re-execute an asynchronous operation managed by `query()` in Anchor. Calling the `start()` method on the query state object triggers a new execution. If a request is already pending, it will be automatically cancelled before the new one starts. ```typescript const dataQuery = query(async (signal) => { const response = await fetch('/api/data', { signal }); return response.json(); }); // Refresh the data function refresh() { dataQuery.start(); } ``` -------------------------------- ### Svelte Integration with mutable() for Automatic Reactivity Source: https://context7.com/beerush-id/anchor/llms.txt Illustrates how to use the `mutable()` function from '@anchorlib/svelte' for state management in Svelte applications. This approach leverages Svelte's built-in reactivity system for seamless state updates and UI synchronization. ```svelte

    Count: {state.count}

    {state.user.name} ({state.user.online ? 'Online' : 'Offline'})

      {#each state.todos as todo, i}
    • {todo}
    • {/each}
    ``` -------------------------------- ### Basic Query State Handling with TypeScript Source: https://github.com/beerush-id/anchor/blob/main/docs/react/state/async-handling.md Demonstrates the basic usage of the `query()` function to create a reactive container for an asynchronous operation. It shows how to access the status and data of the query, which automatically starts upon creation. This is useful for general async tasks with Promises. ```typescript import { query } from '@anchorlib/react'; // Define an async operation const userQuery = query(async (signal) => { const response = await fetch('/api/user', { signal }); return response.json(); }); // Access the state console.log(userQuery.status); // 'pending' console.log(userQuery.data); // undefined initially ``` -------------------------------- ### Sequential Query Execution with Dependencies in TypeScript Source: https://github.com/beerush-id/anchor/blob/main/docs/react/state/async-handling.md Illustrates how to execute queries sequentially, where one query depends on the result of another. This can be achieved using `effect()` or by directly calling `start()` after awaiting the `promise` of the preceding query. It shows fetching user data and then fetching posts related to that user. Requires `mutable`, `query`, and `effect` functions. ```typescript const store = mutable({ userId: 1, userQuery: query( async (signal) => { const res = await fetch(`/api/users/${store.userId}`, { signal }); return res.json(); }, null, { deferred: true } ), postsQuery: query(fetchPosts, [], { deferred: true }), async loadUserAndPosts() { // Sequential: wait for user first await this.userQuery.promise; // Then load posts with user ID if (this.userQuery.status === 'success') { this.postsQuery.start(); } } }); // Or use effect for automatic re-fetching effect(() => { if (store.userQuery.status === 'success') { store.postsQuery.start(); } }); ``` -------------------------------- ### Reactive Storage Adapters with @anchorlib/storage Source: https://context7.com/beerush-id/anchor/llms.txt Provides examples of using MemoryStorage, SessionStorage, and PersistentStorage from '@anchorlib/storage' for reactive state management. These adapters automatically handle persistence to browser storage mechanisms like sessionStorage and localStorage, and offer a functional API for session and persistent storage. ```typescript import { MemoryStorage, SessionStorage, PersistentStorage } from '@anchorlib/storage'; import { anchor, subscribe } from '@anchorlib/core'; // Memory storage (no persistence) const memStorage = new MemoryStorage(); memStorage.set('key', { value: 123 }); console.log(memStorage.get('key')); // { value: 123 } // SessionStorage with reactive state (persists per session) const settings = anchor({ theme: 'dark', fontSize: 14, notifications: true }); const sessionStorage = new SessionStorage('app-settings', settings); subscribe(settings, (state) => { sessionStorage.set('settings', state); }); // Load from storage on init const saved = sessionStorage.get('settings'); if (saved) { anchor.assign(settings, saved); } // PersistentStorage using localStorage (persists across sessions) const userPrefs = anchor({ language: 'en', theme: 'light' }); const persistentStorage = new PersistentStorage('user-prefs', userPrefs); // Subscribe to changes and persist subscribe(userPrefs, (state) => { persistentStorage.set('prefs', state); }); // Functional API for session and persistent storage import { session, persistent } from '@anchorlib/storage'; // Create reactive session storage const sessionState = session('my-session', { counter: 0, items: [] }); // Create reactive persistent storage const persistentState = persistent('my-data', { username: '', lastLogin: null }); // Direct mutations are automatically persisted sessionState.counter++; persistentState.username = 'john_doe'; // Disconnect from storage session.leave(sessionState); persistent.leave(persistentState); ``` -------------------------------- ### Local State with Mutable within a React Setup Function Source: https://github.com/beerush-id/anchor/blob/main/docs/react/state/advanced.md Illustrates local state management within an Anchor React component using `setup` and `mutable`. This state is scoped to the component instance, ensuring automatic garbage collection and isolation. Ideal for transient UI interaction state. ```tsx import { setup, mutable } from '@anchorlib/react'; export const Counter = setup(() => { // This state is local to this instance of Counter const state = mutable({ count: 0 }); return ( ); }); ``` -------------------------------- ### Anchor vs. React Lifecycle and Effects Comparison Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-system-prompt.md Compares Anchor's reactivity primitives (`effect`, `onMount`) with React's `useEffect`. Highlights differences in execution timing, dependency tracking, and usage scenarios. ```tsx // ❌ React - runs after render, needs dependency array // useEffect(() => { // console.log(user.name); // }, [user.name]); // Manual dependencies // ✅ Anchor effect() - runs immediately, auto-tracks // effect(() => { // console.log(user.name); // Auto-tracked // }); // ✅ Anchor onMount() - like useEffect with empty deps // onMount(() => { // fetchData(); // Runs once after mount // }); ``` -------------------------------- ### Spreading Props in Setup Pitfall Source: https://github.com/beerush-id/anchor/blob/main/docs/react/ai-knowledge-base.md Highlights an error scenario when spreading props directly within the setup function. Anchor.js throws an error because props are reactive proxies and cannot be spread directly in this context. The recommended approach is to use props.$omit([...]) to explicitly select or exclude specific props if needed. ```tsx const divProps = { ...props }; // Error! Use props.$omit([...]) ``` -------------------------------- ### Providing Initial Data to Anchor Queries Source: https://github.com/beerush-id/anchor/blob/main/docs/react/state/async-handling.md Demonstrates how to supply initial data to a `query()` from Anchor. This is useful for preventing `undefined` states before the asynchronous operation completes, allowing for immediate safe rendering of data, such as an empty array for a list of items. ```typescript const todosQuery = query( async (signal) => { const response = await fetch('/api/todos', { signal }); return response.json(); }, [] // Initial empty array ); // Safe to render immediately console.log(todosQuery.data.length); // 0 ```