Installation

Install Package

bash
1npm install react-foam

Basic Setup

typescript
1import { createStore } from 'react-foam';

Core Concepts

Stores

A store in React Foam is created using the createStore function. Each store is completely independent and manages its own state:
typescript
1interface UserState {
2 name: string;
3 email: string;
4 isLoggedIn: boolean;
5}
6
7const useUserStore = createStore<UserState>({
8 name: '',
9 email: '',
10 isLoggedIn: false
11});

State Updates

State updates are performed using the setState method, which accepts either a new state object or an updater function:
typescript
1// Direct state update
2useUserStore.setState({
3 name: 'John Doe',
4 email: 'john@example.com',
5 isLoggedIn: true
6});
7
8// Functional update
9useUserStore.setState(state => ({
10 ...state,
11 name: 'Jane Doe'
12}));

Selective Subscriptions

Components can subscribe to specific parts of the state using selectors, ensuring minimal re-renders:
typescript
1function UserName() {
2 // Only re-renders when name changes
3 const name = useUserStore(state => state.name);
4
5 return <span>{name}</span>;
6}

Optimizing Derived State with memo

When a selector creates a new object or array (e.g., using .filter() or by returning {...}), it can cause unnecessary re-renders. React Foam provides a memo utility to solve this problem elegantly.
typescript
1import { createStore, memo } from 'react-foam';
2
3const useUserStore = createStore({ user: { name: 'Alex', age: 30 }, lastLogin: Date.now() });
4
5function UserCard() {
6 // Without memo, this component would re-render when lastLogin changes.
7 // With memo, it only re-renders when user.name changes.
8 const { name } = useUserStore(
9 memo(state => ({ name: state.user.name }))
10 );
11
12 return <div>{name}</div>
13}

Advanced Usage

Multiple Stores

You can create and use multiple stores independently:
typescript
1const useThemeStore = createStore({ theme: 'light' });
2
3function App() {
4 const theme = useThemeStore(state => state.theme);
5 const user = useUserStore(state => state);
6
7 return (
8 <div className={theme}>
9 Welcome {user.name}
10 </div>
11 );
12}

Middleware

React Foam supports middleware for logging, persistence, and more.
typescript
1import { createStore, withLogger } from 'react-foam';
2
3const useCounterStore = createStore(
4 { count: 0 },
5 withLogger
6);

Examples

Counter Store

typescript
1const useCounterStore = createStore({ count: 0 });
2
3function Counter() {
4 const { count } = useCounterStore();
5
6 return (
7 <div>
8 <button onClick={() => useCounterStore.setState(s => ({ count: s.count - 1 }))}>
9 -
10 </button>
11 {count}
12 <button onClick={() => useCounterStore.setState(s => ({ count: s.count + 1 }))}>
13 +
14 </button>
15 </div>
16 );
17}

Docs