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
Create a store file
Create a new file called The
store.ts (or store.js) in your project:store.ts
createStore function returns everything you need:useStore: React hook for accessing state in componentsgetState: Function to get current state outside Reactactions: Object containing setter functions (e.g.,setCounter,setMessage)reset: Function to reset state to initial values
Use the store in a component
Import and use the
useStore hook in your React component:App.tsx
Stan.js automatically generates setter functions for each state property. For a property named
counter, you get setCounter.Core Concepts
Automatic Setter Generation
Stan.js automatically generates setter functions for each property in your store:Updating State
You can update state in two ways:Computed Values
Create computed values using getters that automatically update when dependencies change:Selective Re-renders
Stan.js only re-renders components when the specific values they use change:This selective re-rendering is automatic - no selectors or memoization needed!
Complete Example
Here’s a more complete example showing multiple features:Async Operations
Stan.js works seamlessly with async operations:Accessing State Outside React
You can access and update state outside of React components:Data Persistence
Add persistence to any state property using thestorage helper:
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