<!--
Sitemap:
- [rxfy](/index): Typed, normalized, reactive state — built on RxJS
- [Comparison](/comparison): rxfy versus Redux Toolkit, MobX, Jotai, TanStack Query, and TanStack DB
- [Inspired by](/inspired-by): the libraries and ideas rxfy grew out of
- [Agent Skills](/agent-skills): Accurate rxfy context for AI coding assistants
- [Examples](/examples): Runnable apps, from client-only to fully synced
- [Changelog](/changelog)
- [Getting Started](/getting-started)
- [Create Store](/getting-started/create-store): Normalized reactive state in a client-only app
- [Add SSR](/getting-started/add-ssr): Render the first paint on the server, hydrate with no refetch
- [Add Sync Client](/getting-started/add-sync-client): The full stack: the server publishes, the client syncs
- [Core Concepts](/core-concepts): The ideas rxfy is built on
- [Observables](/core-concepts/observables): A value that changes over time, that you can subscribe to
- [Normalization](/core-concepts/normalization): Store each entity once, reference it by id
- [Late Unwrapping](/core-concepts/late-unwrapping): Unwrap async state at the leaf, not the trunk
- [Server-Side Rendering](/core-concepts/ssr): Dehydrate on the server, hydrate with no refetch
- [rxfy](/rxfy): The core package: atoms, lenses, models, and states
- [createModel](/rxfy/create-model): Typed entities in normalized storage
- [defineState](/rxfy/define-state): Typed, normalized state shapes with fetching and mutations
- [createAtom](/rxfy/create-atom): A reactive cell with synchronous get, set, and modify
- [createLens](/rxfy/create-lens): A two-way view into part of an Atom
- [React Bindings](/react): Hooks and helpers for using rxfy in React
- [useStateData](/react/use-state-data): Fetch, normalize, and subscribe to a query
- [useStatePagedData](/react/use-state-paged-data): Paginated and infinite-scroll lists
- [useModelStore](/react/use-model-store): Subscribe to one normalized entity by id
- [useAtom](/react/use-atom): Two-way binding for any IAtom
- [Pending](/react/pending): Render pending, rejected, and fulfilled UI for any observable
- [usePending](/react/use-pending): The status value behind Pending
- [useObservable](/react/use-observable): Bind a raw Observable to React
- [Sync Client in React](/react/sync-client): StoreProvider, useSyncClient, and update handles
- [rxfy-client](/framework/client): The framework-agnostic browser sync runtime
- [createSyncClient](/framework/client/create-sync-client): Connect a transport and drive the sync loop
- [readSsrGrants](/framework/client/read-ssr-grants): Lift SSR-embedded channel grants
- [rxfy-server](/framework/server): Bind Drizzle tables, write, and publish sync updates
- [defineResource](/framework/server/define-resource): Tie a Drizzle table to an rxfy model
- [createSync](/framework/server/create-server): Wire a storage adapter, hub, and secret into a Live object
- [createInMemoryHub](/framework/server/hub): The socket-keyed pub/sub backbone
- [Writes](/framework/server/writes): sync.create / sync.update / sync.delete and touch
- [Storage adapters](/framework/server/storage-adapters): Persist writes with Drizzle or in memory
- [Sync messages](/framework/server/messages): What travels between server and client
- [Grants](/framework/server/grants): The server signs what it serves; the client subscribes with the token
- [rxfy-ws](/framework/ws): The default WebSocket transport
- [createWsServer](/framework/ws/server): Attach a Hub to WebSocket connections
- [createWsClient](/framework/ws/client): The browser transport with reconnect and replay
- [Custom transports](/framework/ws/custom-transport): Bring your own ClientTransport
- [Guides](/guides): Task-focused walkthroughs of common rxfy patterns
- [Pagination and infinite scroll](/guides/pagination): Load and append pages into one normalized list
-->

# createLens \[A two-way view into part of an Atom]

`createLens` makes a **Lens**: a focused, two-way view into an `Atom` — read a slice out,
then write it back. Change detection uses `lodash.isEqual`.

## Why?

A Lens **is an `Atom`** with the same `get()` / `set()` / `modify()` surface, but it points
at *part* of another Atom instead of owning state. So anything that takes an Atom (`useAtom`,
another `createLens`) takes a Lens too.

* **Immutable focus.** `get` reads a slice out; `set` returns a **new** source with the slice
  replaced and leaves the original alone. Compose lenses to reach nested fields.
* **Two-way and live.** Reads flow down, writes flow up, and the view re-derives when the
  source changes elsewhere.
* **Dedupe both ways.** Inbound sync and write-back skip no-op updates, so writing an
  unchanged value won't echo back.

Reach for a Lens when a consumer needs one field of a larger entity without knowing about
the rest.

```ts
import { createAtom, createLens, keyLens } from "rxfy";

const user = createAtom({ id: "1", name: "Alice" });
const name = createLens(user, keyLens("name"));

name.get(); // "Alice"
name.set("Bob");
user.get(); // { id: "1", name: "Bob" }
```

## Signatures

```ts
function createLens<S, T>(source$: IAtom<S>, lens: ILens<S, T>): Lens<S, T>;
function keyLens<S, K extends keyof S>(key: K): ILens<S, S[K]>;
```

The signatures name two different shapes. `ILens<S, T>` is the **optic** you pass in, a pure
view/edit pair that `keyLens` builds for you. `Lens<S, T>` is what `createLens` returns: a
reactive cell implementing [`IAtom<T>`](/rxfy/create-atom), so it drops in anywhere an `Atom`
is expected.

```ts
type ILens<S, T> = {
  get(source: S): T; // read the focused slice out of the source
  set(current: T, source: S): S; // return a NEW source with the slice replaced (immutable)
};

// createLens(...) returns a Lens<S, T>, which implements IAtom<T>:
type Lens<S, T> = IAtom<T>; // get(): T; set(val: T): void; modify(fn: (val: T) => T): void
```

To bind a form input to one field of a stored entity, compose a `keyLens` over a
[`ModelStore.get(id)`](/rxfy/create-model#modelstore-get) handle and drive it with
[`useAtom`](/react/use-atom). Edits flow back into the model store and reach every subscriber
of that entity.
