Skip to main content
This guide will walk you through creating your first stan-js store and using it in a React application. You’ll learn the core concepts and see how easy it is to manage state with stan-js.

Prerequisites

Before you begin, make sure you have:
  • Node.js installed
  • A React project set up (or create one with Vite, Next.js, or Create React App)
  • Stan.js installed (see installation guide)

Creating Your First Store

1

Create a store file

Create a new file called store.ts (or store.js) in your project:
store.ts
import { createStore } from 'stan-js'

export const { useStore, getState, actions, reset } = createStore({
  counter: 0,
  message: 'Hello, Stan!',
  users: [] as Array<string>
})
The createStore function returns everything you need:
  • useStore: React hook for accessing state in components
  • getState: Function to get current state outside React
  • actions: Object containing setter functions (e.g., setCounter, setMessage)
  • reset: Function to reset state to initial values
2

Use the store in a component

Import and use the useStore hook in your React component:
App.tsx
import { useStore } from './store'

const App = () => {
  const { counter, setCounter } = useStore()

  return (
    <div>
      <h1>Counter: {counter}</h1>
      <button onClick={() => setCounter(prev => prev + 1)}>
        Increment
      </button>
      <button onClick={() => setCounter(prev => prev - 1)}>
        Decrement
      </button>
    </div>
  )
}

export default App
Stan.js automatically generates setter functions for each state property. For a property named counter, you get setCounter.
3

Run your app

Start your development server and see your state management in action!
npm run dev
Click the increment and decrement buttons to see the counter update in real-time.

Core Concepts

Automatic Setter Generation

Stan.js automatically generates setter functions for each property in your store:
const { useStore } = createStore({
  count: 0,
  user: '',
  todos: []
})

// Available setters:
// - setCount
// - setUser  
// - setTodos

Updating State

You can update state in two ways:
const { setCounter } = useStore()

// Set a direct value
setCounter(10)

Computed Values

Create computed values using getters that automatically update when dependencies change:
const { useStore } = createStore({
  count: 0,
  get doubleCount() {
    return this.count * 2
  }
})

const Component = () => {
  const { count, doubleCount } = useStore()
  
  return (
    <div>
      <p>Count: {count}</p>
      <p>Double: {doubleCount}</p>
    </div>
  )
}

Selective Re-renders

Stan.js only re-renders components when the specific values they use change:
// This component only re-renders when 'counter' changes
const Counter = () => {
  const { counter } = useStore()
  return <div>{counter}</div>
}

// This component only re-renders when 'message' changes
const Message = () => {
  const { message } = useStore()
  return <div>{message}</div>
}
This selective re-rendering is automatic - no selectors or memoization needed!

Complete Example

Here’s a more complete example showing multiple features:
import { createStore } from 'stan-js'

export const { useStore, actions, reset, getState } = createStore({
  counter: 0,
  message: 'Hello, Stan!',
  get upperCaseMessage() {
    return this.message.toUpperCase()
  },
  users: [] as Array<string>
})

// You can call actions outside React components
export const incrementCounter = () => {
  actions.setCounter(prev => prev + 1)
}

Async Operations

Stan.js works seamlessly with async operations:
const UsersList = () => {
  const { users, setUsers } = useStore()

  const fetchUsers = async () => {
    const response = await fetch('/api/users')
    const data = await response.json()
    setUsers(data)
  }

  return (
    <div>
      <button onClick={fetchUsers}>Fetch Users</button>
      {users.map(user => <div key={user}>{user}</div>)}
    </div>
  )
}

Accessing State Outside React

You can access and update state outside of React components:
import { getState, actions } from './store'

// Get current state
const currentCounter = getState().counter

// Update state
actions.setCounter(100)

// Example: Update from a timer
setInterval(() => {
  actions.setCounter(prev => prev + 1)
}, 1000)

Data Persistence

Add persistence to any state property using the storage helper:
import { createStore } from 'stan-js'
import { storage } from 'stan-js/storage'

export const { useStore } = createStore({
  // This value persists in localStorage
  theme: storage('light'),
  // This value persists with a custom key
  user: storage('', { storageKey: 'currentUser' }),
  // This value doesn't persist
  tempData: ''
})
The storage helper uses localStorage in browsers and MMKV in React Native (when installed).

Next Steps

You now know the basics of stan-js! Here’s what to explore next:

createStore

Learn about all createStore options and methods

Storage & Persistence

Deep dive into data persistence

Scoped Stores

Create isolated store instances with React Context

Vanilla JS

Use stan-js without React

Build docs developers (and LLMs) love