{"id":30882295,"url":"https://github.com/shortwave/watchable","last_synced_at":"2025-09-08T08:45:23.983Z","repository":{"id":57160021,"uuid":"445280816","full_name":"shortwave/watchable","owner":"shortwave","description":"A library to expose state into React","archived":false,"fork":false,"pushed_at":"2022-01-07T16:00:03.000Z","size":158,"stargazers_count":33,"open_issues_count":0,"forks_count":1,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-08-24T21:56:15.146Z","etag":null,"topics":["react","state-management","typescript"],"latest_commit_sha":null,"homepage":"https://www.shortwave.com/blog/watchables-realtime-react-without-redux/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/shortwave.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-01-06T19:04:15.000Z","updated_at":"2023-06-14T01:25:36.000Z","dependencies_parsed_at":"2022-09-09T05:20:07.441Z","dependency_job_id":null,"html_url":"https://github.com/shortwave/watchable","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/shortwave/watchable","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shortwave%2Fwatchable","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shortwave%2Fwatchable/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shortwave%2Fwatchable/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shortwave%2Fwatchable/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/shortwave","download_url":"https://codeload.github.com/shortwave/watchable/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shortwave%2Fwatchable/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274159557,"owners_count":25232636,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-08T02:00:09.813Z","response_time":121,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["react","state-management","typescript"],"created_at":"2025-09-08T08:45:11.123Z","updated_at":"2025-09-08T08:45:23.956Z","avatar_url":"https://github.com/shortwave.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Watchable\n\nA small library to expose state into React.\n\n## Features\n\n- 🧑‍🏫 **Easy to learn:** Small API surface - all you need are two classes and a hook to get started.\n- 🤏 **Small:** 2.15 kb bundle minified and gzipped. Supports ESM and tree shaking.\n- ⚡ **Fast:** Minimized renders with built-in memoization.\n- ⚛️  **React:** Built for React in mind with hooks built in.\n- ⌨️  **Typescript:** It's written in TypeScript and types are exported along with the library.\n\n## Introduction\n\nWatchables are objects that store your application state. They can be subscribed too for updates, but at the same time the existing value can be retrieved synchronously, even when transforms are applied. This library pairs well with React and comes with a couple of [hooks](https://github.com/shortwave/watchable/blob/main/src/hooks.ts) such as `useWatchable` and `useMemoizedWatchable`.\n\nA watchable can be used a simple way to expose state into your React components without needing a full blown state management system like Redux or MobX.\n\nSee our [blog post](https://www.shortwave.com/blog/watchables-realtime-react-without-redux/) for more background on how this library came to be.\n\n## Basic usage\n\n```typescript\nimport { WatchableSubject } from '@shortwave/watchable';\n\nconst v = WatchableSubject.of(0);\n\nconsole.log(`Count is at ${w.getValue()}`);\n// output: Count is at 0\n\n/* Subscriptions to a value synchronously fires, so updates cannot be missed. */\nv.watch((count) =\u003e {\n  console.log(`Count is ${w.getValue()}`);\n});\n// output: Count is 0\n\nv.update(1);\n// output: Count is 1\n\nv.update(1);\n// no output - the value is memoized\n```\n\n## Advanced usage\n\nSee the example/ and tests/ directories for the full API and more examples.\n\n#### `watchable.map(mapper: (t: T) =\u003e U): Watchable\u003cU\u003e`\n\nUseful for transforming internal state to external state or dropping private data.\n\n```typescript\nconst v = WatchableSubject.of(0);\nconst u = v.map((n) =\u003e `Count is ${n}`);\nu.watch((s) =\u003e console.log(s));\n// output: Count is 0\nv.update(6);\n// output: Count is 6\n```\n\n#### `watchable.withHooks({setup, tearDown}): Watchable\u003cU\u003e`\n\nAllows for tracking subscriptions so you can cleanup other resources when the value isn't being watched anymore (for example, setting up and tearing down a websocket connection).\n\n```typescript\nconst v = WatchableSubject.of(0);\nconst u = v.withHooks({\n  setup: () =\u003e console.log(\"First watcher started!\"),\n  tearDown: () =\u003e console.log(\"Last watcher stopped!\"),\n});\nconst unsub1 = u.watch((s) =\u003e { /* noop */ });\n// output: First watcher started!\nconst unsub2 = u.watch((s) =\u003e { /* noop */ });\nunsub1();\n// no output\nunsub2();\n// output: Last watcher stopped!\n```\n\n#### `watchable.toPromise()`\n\nUseful in imperative code an async callback where you need to access a value that may still be loading.\n\n```typescript\nconst v = WatchableSubject.empty\u003cnumber\u003e();\nv.toPromise().then((value) =\u003e {\n  console.log(`Count is ${value}`);\n});\nsetTimeout(() =\u003e {\n  v.update(0);\n  // output: Count is 0\n  v.update(1);\n  // No output - promise is resolved already\n}, 150);\n```\n\n#### `watchable.snapshot()`\n\nCan be used to get only the current value, or the first value after loading. An example of where this can be used is to perform searches against frequently updated values.\n\n```typescript\nconst v = WatchableSubject.of\u003cnumber\u003e(1);\nconst snap = v.snapshot();\nconsole.log(`Snapshot value ${snap.getValue()}`);\n// output: Snapshot value 1\nv.update(2);\nconsole.log(`Snapshot value ${snap.getValue()}`);\n// output: Snapshot value 1\n```\n\n#### `partialCombineWatchable`\n\nWe frequently use this to create \"batch\" versions of hooks, this allows for combining a map of several watchables into one. This omits any empty watchables.\n\n```typescript\nimport {partialCombineWatchable, Watchable, WatchableSubject} from \"@shortwave/watchable\";\n\nconst mapOfWatchables: Map\u003cstring, Watchable\u003cnumber\u003e\u003e = new Map([\n  ['a', WatchableSubject.of(1)],\n  ['b', WatchableSubject.of(2)],\n  ['c', WatchableSubject.empty()],\n]);\nconst watchableMap: Watchable\u003cMap\u003cstring, number\u003e\u003e = partialCombineWatchable(mapOfWatchables);\nconsole.log(watchableMap.getValue());\n// output: Map([['a', 1], ['b', 2]])\n```\n\nHere's an example of using this to create a \"batch\" version of a hook.\n\n```typescript\nimport {useMemoizedWatchable, partialCombineWatchable} from \"@shortwave/watchable\";\n\nfunction useBatchOnlineStatusService(users: UserId[]): Map\u003cUserId, OnlineStatus\u003e {\n  const service = useOnlineStatusService();\n  const value = useMemoizedWatchable(() =\u003e {\n    const statusByUser: Map\u003cUserId, Watchable\u003cOnlineStatus\u003e\u003e = new Map(users.map((userId) =\u003e\n      [userId, service.watchOnlineStatus(userId)]\n    ));\n    return partialCombineWatchable(statusByUser);\n  }, [service, users]);\n  // partialCombineWatchable is never empty, but we need to make typescript happy and provide\n  // a default loading value.\n  return value ?? new Map();\n}\n```\n\n## Contributing\n\nWe're using [DTS](https://github.com/weiran-zsd/dts-cli) to manage this library.\n\nThe library resides inside `/src`, and there is a [Vite-based](https://vitejs.dev) playground for it inside `/example`.\n\nThe recommended workflow is to run DTS in one terminal:\n\n```bash\nnpm start # or yarn start\n```\n\nThis builds to `/dist` and runs the project in watch mode so any edits you save inside `src` causes a rebuild to `/dist`.\n\nThen run the example inside another:\n\n```bash\ncd example\nnpm i # or yarn to install dependencies\nnpm start # or yarn start\n```\n\nThe default example imports and live reloads whatever is in `/dist`, so if you are seeing an out of date component, make sure DTS is running in watch mode like we recommend above. \n\nTo do a one-off build, use `npm run build` or `yarn build`.\n\nTo run tests, use `npm test` or `yarn test`.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshortwave%2Fwatchable","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fshortwave%2Fwatchable","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshortwave%2Fwatchable/lists"}