Skip to main content

API Reference Overview

This section provides comprehensive documentation for all Refract APIs, including core functions, hooks, utilities, and configuration options. Each API is documented with detailed descriptions, parameters, return values, and practical examples.

Core APIs

Application Management

  • createApp - Initialize and configure a Refract application
  • mount - Mount the application to a DOM element

Component System

  • createComponent - Create reactive components
  • memo - Optimize component re-rendering
  • lazy - Code-split components for better performance

State Management

Effects and Lifecycle

  • useEffect - Handle side effects and lifecycle events
  • useFlash - Execute effects after render for animations
  • useOptic - Create and use reusable logic patterns

Lens System

  • useLens - Access component-scoped reactive features
  • batch - Optimize multiple state updates

Quick Reference

Import Statements

// Core functions
import {
createApp,
createComponent,
createRefraction
} from 'refract';

// Hooks (used within components via lens)
import {
useRefraction,
useEffect,
useOptic,
useFlash
} from 'refract';

// Utilities
import {
memo,
lazy,
Suspense
} from 'refract';

Basic Usage Patterns

Creating an Application

import { createApp } from 'refract';
import App from './App';

createApp(App).mount('#root');

Creating a Component

import { createComponent } from 'refract';

const MyComponent = createComponent(({ lens, ...props }) => {
const state = lens.useRefraction(initialValue);

lens.useEffect(() => {
// Side effects here
}, [dependencies]);

return <JSX />;
});

Managing State

// Local state
const count = lens.useRefraction(0);

// Global state
import { createRefraction } from 'refract';
export const globalState = createRefraction(initialValue);

// Derived state
const doubled = lens.useDerived(() => count.value * 2, [count]);

Handling Effects

// Mount effect
lens.useEffect(() => {
console.log('Component mounted');
return () => console.log('Component unmounting');
}, []);

// Update effect
lens.useEffect(() => {
console.log('Value changed:', value);
}, [value]);

// Flash effect (after render)
lens.useFlash(() => {
animateElement();
}, [trigger]);

API Categories

🏗️ Application & Components

Functions for creating and managing applications and components.

APIDescriptionUse Case
createApp()Initialize applicationApp setup
createComponent()Create reactive componentComponent definition
memo()Memoize componentPerformance optimization
lazy()Lazy load componentCode splitting

🔄 State Management

APIs for managing reactive state and computed values.

APIDescriptionUse Case
useRefraction()Create reactive stateLocal component state
createRefraction()Create global stateShared state
useDerived()Computed valuesDerived state
batch()Batch updatesPerformance

Effects & Lifecycle

Functions for handling side effects and component lifecycle.

APIDescriptionUse Case
useEffect()Side effectsData fetching, subscriptions
useFlash()Post-render effectsAnimations, DOM manipulation
useOptic()Reusable logicCustom hooks

🔍 Lens System

The lens provides scoped access to reactive features within components.

APIDescriptionUse Case
lens.useRefraction()Scoped stateComponent state
lens.useEffect()Scoped effectsComponent effects
lens.useOptic()Scoped opticsComponent logic
lens.batch()Scoped batchingComponent updates

Type Definitions

Core Types

// Component definition
type Component<P = {}> = (props: P & { lens: Lens }) => JSX.Element;

// Refraction (reactive state)
interface Refraction<T> {
value: T;
set: (value: T | ((prev: T) => T)) => void;
subscribe: (callback: (value: T) => void) => () => void;
}

// Lens interface
interface Lens {
useRefraction<T>(initialValue: T): Refraction<T>;
useDerived<T>(compute: () => T, deps: any[]): Refraction<T>;
useEffect(effect: () => void | (() => void), deps?: any[]): void;
useFlash(effect: () => void, deps?: any[]): void;
useOptic<T>(optic: () => T, deps: any[]): T;
batch(fn: () => void): void;
}

// Application instance
interface App {
mount(selector: string | Element): void;
unmount(): void;
}

Effect Types

// Effect function
type EffectFunction = () => void | (() => void);

// Effect dependencies
type EffectDeps = any[] | undefined;

// Flash effect (no cleanup)
type FlashFunction = () => void;

Optic Types

// Optic function
type OpticFunction<T> = () => T;

// Optic dependencies
type OpticDeps = any[];

Error Handling

Common Error Patterns

// Safe async effects
lens.useEffect(() => {
let cancelled = false;

fetchData()
.then(data => {
if (!cancelled) {
setState(data);
}
})
.catch(error => {
if (!cancelled) {
setError(error.message);
}
});

return () => {
cancelled = true;
};
}, []);

// Error boundaries
const ErrorBoundary = createComponent(({ lens, children }) => {
const hasError = lens.useRefraction(false);
const error = lens.useRefraction(null);

if (hasError.value) {
return (
<div>
<h2>Something went wrong</h2>
<p>{error.value?.message}</p>
<button onClick={() => hasError.set(false)}>
Try again
</button>
</div>
);
}

return children;
});

Performance Guidelines

Optimization Strategies

  1. Use memo() for expensive components

    const ExpensiveComponent = memo(createComponent(({ lens, data }) => {
    // Expensive rendering logic
    }));
  2. Batch related state updates

    lens.batch(() => {
    setState1(value1);
    setState2(value2);
    setState3(value3);
    });
  3. Use specific effect dependencies

    // ✅ Good - specific dependencies
    lens.useEffect(() => {
    fetchUser(userId);
    }, [userId]);

    // ❌ Bad - too broad
    lens.useEffect(() => {
    fetchUser(userId);
    }, [user]); // Runs when any user property changes
  4. Lazy load components

    const LazyComponent = lazy(() => import('./HeavyComponent'));

    <Suspense fallback={<Loading />}>
    <LazyComponent />
    </Suspense>

Migration Guide

From React

ReactRefractNotes
useStatelens.useRefractionSimilar API, automatic reactivity
useEffectlens.useEffectSame dependency system
useMemolens.useDerivedReactive computed values
useCallbacklens.useOpticFor reusable logic
React.memomemoSame optimization concept
React.lazylazySame code splitting

Key Differences

  1. No setState needed - Refractions update automatically
  2. Lens system - Scoped access to reactive features
  3. Built-in reactivity - No manual dependency tracking
  4. Optics - More powerful than custom hooks

Next Steps