useStorken Hook
The React hook for accessing and managing state in Storken.
Syntax
const [value, setValue, reset, loading, update, plugins] = useStorken<T>(key, initialValue?)
Parameters
key
string
- The unique identifier for the state value
initialValue
T
- Optional initial value if not set in store config
Return Value
Returns a tuple with 6 elements:
value: T
- Current state valuesetValue: (value: T | (prev: T) => T) => void
- State setterreset: () => void
- Reset to initial valueloading: boolean
- Loading state for async operationsupdate: (...args) => void
- Trigger getter functionplugins: Record<string, any>
- Plugin instances
Examples
Basic Usage
function Counter() {
const [count, setCount] = useStorken('count', 0)
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
)
}
With Reset
function Settings() {
const [settings, setSettings, resetSettings] = useStorken('settings', {
theme: 'light',
notifications: true
})
return (
<div>
<button onClick={() => setSettings({ ...settings, theme: 'dark' })}>
Toggle Theme
</button>
<button onClick={resetSettings}>
Reset to Defaults
</button>
</div>
)
}
With Loading State
function UserProfile() {
const [user, , , loading, refetch] = useStorken('user')
useEffect(() => {
refetch() // Trigger getter
}, [refetch])
if (loading) return <Spinner />
if (!user) return <div>No user found</div>
return <div>Welcome, {user.name}!</div>
}
With TypeScript
interface User {
id: string
name: string
email: string
}
function UserCard() {
const [user, setUser] = useStorken<User | null>('user', null)
if (!user) return null
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
)
}
Destructuring Pattern
// Only get what you need
const [count] = useStorken('count', 0) // Read-only
const [, setTheme] = useStorken('theme') // Write-only
const [user, , resetUser] = useStorken('user') // Read and reset
const [data, , , loading] = useStorken('data') // Read with loading
💡 Tips
- • The hook automatically subscribes to state changes
- • Components re-render only when their specific state changes
- • You can use the same key in multiple components to share state
- • Loading state is automatically managed for async operations