API Reference

Complete API reference for Storken state management library.

Core Functions

create(config?)

Creates a new Storken store instance with optional configuration.

const [useStorken, get, set, sky] = create({
  initialValues: { count: 0 },
  getters: { /* ... */ },
  setters: { /* ... */ },
  plugins: { /* ... */ }
})

Returns:

  • useStorken - React hook for state management
  • get - Get state value synchronously
  • set - Set state value synchronously
  • sky - Sky instance for advanced usage

useStorken<T>(key, initialValue?)

React hook for accessing and managing state.

const [
  value,      // Current state value
  setValue,   // State setter function
  resetValue, // Reset to initial value
  loading,    // Loading state for async operations
  update,     // Trigger getter function
  plugins     // Plugin instances
] = useStorken<number>('counter', 0)

Parameters:

  • key - String identifier for the state
  • initialValue (optional) - Initial value if not set in config

Configuration Types

StorkenConfig

Main configuration object for creating stores.

interface StorkenConfig {
  initialValues?: Record<string, any>
  getters?: Record<string, StorkenGetter>
  setters?: Record<string, StorkenSetter>
  plugins?: StorkenPlugins
  options?: StorkenOptions
}

Advanced Usage

Getters (Async Data Fetching)

const [useStorken] = create({
  getters: {
    user: async () => {
      const res = await fetch('/api/user')
      return res.json()
    }
  }
})

function UserProfile() {
  const [user, , , loading, refetch] = useStorken<User>('user')
  
  if (loading) return <div>Loading...</div>
  return <div>{user?.name}</div>
}

Setters (Side Effects)

const [useStorken] = create({
  setters: {
    user: async (storken, user: User) => {
      await fetch(`/api/user/${user.id}`, {
        method: 'PUT',
        body: JSON.stringify(user)
      })
    }
  }
})

Plugin System

const persistencePlugin = (storken) => {
  const saved = localStorage.getItem(`storken_${storken.key}`)
  if (saved) storken.set(JSON.parse(saved))
  
  storken.on('set', (value) => {
    localStorage.setItem(`storken_${storken.key}`, JSON.stringify(value))
  })
  
  return {
    clear: () => localStorage.removeItem(`storken_${storken.key}`)
  }
}

Types & Interfaces

StorkenHook Return Type

The array returned by the useStorken hook.

type StorkenReturn<T> = [
  value: T,                    // Current state value
  setValue: (value: T | ((prev: T) => T)) => void,  // Setter function
  resetValue: () => void,      // Reset to initial value
  loading: boolean,            // Loading state for async operations
  update: (...args: any[]) => void,  // Trigger getter function
  plugins: Record<string, any> // Plugin instances
]

StorkenGetter

Function signature for async data fetching.

type StorkenGetter = (
  storken: StorkenInstance,
  ...args: any[]
) => Promise<any> | any

StorkenSetter

Function signature for setters with side effects.

type StorkenSetter = (
  storken: StorkenInstance,
  value: any,
  ...args: any[]
) => Promise<void> | void

StorkenPlugin

Plugin function signature for extending Storken.

type StorkenPlugin = (
  storken: StorkenInstance
) => any | void

Sky Instance Methods

sky.get(key)

Get state value synchronously without React hook.

// Outside React components
const currentCount = sky.get('counter')
console.log('Current count:', currentCount)

sky.set(key, value)

Set state value synchronously without React hook.

// From event handlers or async functions
sky.set('counter', 10)

// With function updater
sky.set('counter', (prev) => prev + 1)

sky.reset(key)

Reset state to initial value.

// Reset to initial value
sky.reset('counter')

sky.subscribe(key, callback)

Subscribe to state changes.

const unsubscribe = sky.subscribe('counter', (value) => {
  console.log('Counter changed to:', value)
})

// Later, unsubscribe
unsubscribe()

Advanced Patterns

Optimistic Updates

Update UI optimistically while saving to server.

const [useStorken] = create({
  setters: {
    todos: async (storken, todos: Todo[]) => {
      // Optimistically update UI
      storken.set(todos)
      
      try {
        await fetch('/api/todos', {
          method: 'PUT',
          body: JSON.stringify(todos)
        })
      } catch (error) {
        // Revert on error
        storken.reset()
        throw error
      }
    }
  }
})

Computed Values

Create derived state from existing values.

const [useStorken] = create({
  initialValues: {
    todos: [],
    filter: 'all'
  },
  getters: {
    filteredTodos: (storken) => {
      const todos = storken.get('todos')
      const filter = storken.get('filter')
      
      if (filter === 'active') {
        return todos.filter(t => !t.completed)
      } else if (filter === 'completed') {
        return todos.filter(t => t.completed)
      }
      return todos
    }
  }
})

Middleware Pattern

Intercept and modify state changes.

const loggingPlugin = (storken) => {
  const originalSet = storken.set.bind(storken)
  
  storken.set = (value) => {
    console.log(`[${storken.key}] Setting:`, value)
    originalSet(value)
  }
}

const [useStorken] = create({
  plugins: {
    logger: loggingPlugin
  }
})

Cross-Component Communication

Share state between unrelated components.

// store.ts
export const [useStorken, get, set, sky] = create({
  initialValues: {
    notifications: [],
    theme: 'light'
  }
})

// Component A
function Settings() {
  const [theme, setTheme] = useStorken('theme')
  return (
    <select value={theme} onChange={e => setTheme(e.target.value)}>
      <option value="light">Light</option>
      <option value="dark">Dark</option>
    </select>
  )
}

// Component B (anywhere in the tree)
function App() {
  const [theme] = useStorken('theme')
  return <div className={theme}>...</div>
}

🎯 Best Practices

  • • Use TypeScript for full type safety
  • • Keep state minimal and derived values in getters
  • • Use setters for async operations with side effects
  • • Leverage plugins for cross-cutting concerns
  • • Use sky instance for non-React contexts