Store Creation

Learn how to create and configure stores in Storken for optimal state management.

Basic Store

The simplest way to create a store is with initial values:

import { create } from 'storken';

const [useStorken, getStore, setStore, sky] = create({
  initialValues: {
    counter: 0,
    theme: 'light',
    user: null
  }
});

Return Values

useStorken

React hook for accessing state in components

getStore

Get current state value outside React components

setStore

Set state value outside React components

sky

The Sky instance for advanced usage and non-React contexts

Advanced Configuration

Async Getters

Load data asynchronously when a value is first accessed:

const [useStorken] = create({
  initialValues: {
    posts: []
  },
  
  getters: {
    posts: async () => {
      const response = await fetch('/api/posts');
      return response.json();
    }
  }
});

Async Setters

Add side effects when setting values:

const [useStorken] = create({
  initialValues: {
    user: null
  },
  
  setters: {
    user: async (storken, value) => {
      // Save to backend
      await fetch('/api/user', {
        method: 'PUT',
        body: JSON.stringify(value)
      });
      
      // Log the change
      console.log('User updated:', value);
      
      // Update other related state
      storken.set('lastUpdated', Date.now());
    }
  }
});

Plugins

Extend your store with plugins for persistence, logging, and more:

import { create } from 'storken';
import { persistPlugin } from 'storken/plugins';

const [useStorken] = create({
  initialValues: {
    settings: {}
  },
  
  plugins: {
    persist: persistPlugin({
      key: 'app-settings',
      storage: localStorage
    })
  }
});

Best Practices

  • Keep stores focused on a single domain or feature
  • Use TypeScript for better type safety and autocomplete
  • Export hooks and utilities from a central store file
  • Use async setters for API calls and side effects
  • Leverage getters for lazy loading expensive data

💡 Pro Tip

You can create multiple stores for different parts of your application. This helps with code organization and bundle splitting!