> **Status:** Published
> **Date:** 2026-09-12
> **Scope**: API Reference
> **Standard**: Memorio API Specification v5
>
---
# State - Memorio

> ✅ **Universal**: Works in Browser, Node.js, Deno, and Edge Workers

State is a reactive global state manager using JavaScript Proxies. It's simple, powerful, and requires no setup. Data persists only in memory during the session.

## Installation

```bash
npm install memorio
```

```javascript
import { state } from 'memorio';
```

That's it. `state` is ready to use.

> **Classic `import`**: `state` is also available as a named export from the global entrypoint.
> `import 'memorio/global'` exposes the same proxy as `globalThis.state`.

---

## Quick Examples

### Example 1: Basic Usage

```javascript
// Set a value
state.name = 'Mario';
state.age = 25;

// Get a value
console.debug(state.name); // "Mario"

// Simple object
state.user = { name: 'Luigi', level: 1 };
```

### Example 2: Intermediate

```javascript
// Array operations
state.items = [1, 2, 3];
state.items.push(4);
console.debug(state.items); // [1, 2, 3, 4]

// Nested objects
state.config = { theme: 'dark', lang: 'en' };
state.config.theme = 'light';

// List all states
console.debug(state.list);
```

### Example 3: Advanced

```javascript
// Lock state to prevent modifications
state.frozenConfig = { maxUsers: 100 };
state.frozenConfig.lock();
// Now state.frozenConfig cannot be modified

// Path tracking
const path = state.user.path;
console.debug(path.name); // "user"
console.debug(path.profile.name); // "user.profile"

// Get full path as string
console.debug(state.user.__path); // "state.user"

// Protected keys (internal use)
console.debug(protect); // Array of protected keys
```

---

## API Reference

### Properties

| Property | Type | Description |
|----------|------|-------------|
| `state.list` | Array | Get all current state keys (deep copy) |
| `state.path` | Object | Get path tracker for current location |
| `state.__path` | string | Get full path as string |

### Methods

| Method | Parameters | Description |
|--------|------------|-------------|
| `state.remove(key)` | `key: string` | Remove a specific state |
| `state.removeAll()` | none | Clear all states |

### Lock

`state` exposes two lock scopes with distinct method names.

**Global lock** - freeze the entire `state` tree at once:

```javascript
state.lock();
state.user = { name: 'Sara' };   // Error: state is locked
state.user.name = 'Luigi';       // Error: state is locked
state.lock();                    // (safe to call again)
state.unlock();                  // resume all writes
```

**Per-key lock** - freeze a single first-level node:

```javascript
state.myArray = [1, 2, 3];
state.myArray.lock();

// While locked, reassigning the key, mutating the node, array methods,
// and deleting its properties all fail:
state.myArray.push(4);   // Error: state 'myArray' is locked
state.myArray[0] = 9;    // Error: state 'myArray' is locked
delete state.myArray[0]; // Error: state 'myArray' is locked
state.myArray = [];      // Error: state 'myArray' is locked

state.myArray.unlock();  // Resume writes to myArray only
```

Per-key locking is **first-level only**: `state.a.lock()` does not transitively lock
`state.a.b`. Lock each descendant explicitly (`state.a.b.lock()`), or use the global
`state.lock()` for whole-subtree immutability. While a key is per-key locked, every other
top-level key remains writable.

---

## How It Works

Memorio uses JavaScript `Proxy` to intercept get/set operations on the global `state` object. This allows:

1. **Reactivity** - Any change can trigger observers
2. **Nested objects** - Deep path tracking
3. **Type safety** - Full TypeScript support

---

## Platform Notes

| Platform | Support | Notes |
|----------|---------|-------|
| Browser | ✅ Full | In-memory, lost on refresh |
| Node.js | ✅ Full | In-memory, lost on restart |
| Deno | ✅ Full | In-memory, lost on restart |
| Edge Workers | ✅ Full | In-memory, lost on function cold start |

**Note**: In server environments (Node.js/Deno), use `memorio.createContext()` for request isolation.

---

## Best Practices

1. Use descriptive keys: `state.userProfile` not `state.up`
2. Group related data: `state.cart.items` not `state.cartItems`
3. Lock static config: `state.appConfig.lock()`
4. Clean up on logout: `state.removeAll()`
5. Use path tracking for debugging: `state.myData.__path`

---

## Common Errors

```javascript
// Error: protected key
state._internal = 'value';
// Output: "key _internal is protected"

// Error: locked state
state.locked = { x: 1 };
state.locked.lock();
state.locked.x = 2;
// Output: "Error: state 'locked' is locked"
```
