{"id":28153228,"url":"https://github.com/chuanqisun/react-agent-hooks","last_synced_at":"2025-05-15T05:13:33.123Z","repository":{"id":287066908,"uuid":"963356115","full_name":"chuanqisun/react-agent-hooks","owner":"chuanqisun","description":"Turn React hooks into LLM tools","archived":false,"fork":false,"pushed_at":"2025-04-28T20:32:25.000Z","size":1018,"stargazers_count":71,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-28T20:45:54.283Z","etag":null,"topics":["genui","library","llmstxt","mcp","react","react-hooks"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chuanqisun.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-04-09T14:54:43.000Z","updated_at":"2025-04-28T20:32:28.000Z","dependencies_parsed_at":"2025-04-09T20:21:56.371Z","dependency_job_id":"d1badff0-88a1-4173-99ef-981ed7cc863e","html_url":"https://github.com/chuanqisun/react-agent-hooks","commit_stats":null,"previous_names":["chuanqisun/react-agent-hooks"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chuanqisun%2Freact-agent-hooks","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chuanqisun%2Freact-agent-hooks/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chuanqisun%2Freact-agent-hooks/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chuanqisun%2Freact-agent-hooks/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chuanqisun","download_url":"https://codeload.github.com/chuanqisun/react-agent-hooks/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254276422,"owners_count":22043869,"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","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":["genui","library","llmstxt","mcp","react","react-hooks"],"created_at":"2025-05-15T05:13:30.711Z","updated_at":"2025-05-15T05:13:33.110Z","avatar_url":"https://github.com/chuanqisun.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# React Agent Hooks\n\n| Agentic Counter Demo                                                                                                                                        | Agentic Todo Demo                                                                                                                                                    |\n| :---------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/edit/react-agentic-counter?file=src%2Fmain.jsx) | [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/chuanqisun/react-agent-hooks?file=src%2Fmain.jsx) |\n\nTurn React Hooks into LLM Tools\n\n- 🪝 Familiar: same semantics as React hooks\n- 🤝 Symbiotic: human interface and Agent interface derived from the same state.\n- 🛡️ Safe: developer controls the schema for Agentic state change.\n- ➕ Incremental adoption: use as much or as little as you want.\n- 📦 Composable: fully interoperable with classic React hooks.\n- 🔮 Future-ready: forward-compatible with MCP and llms.txt.\n\n**Before**\n\n```jsx\nimport { useCallback, useState } from \"react\";\n\nfunction MyComponent() {\n  const [name, setName] = useState(\"John Doe\");\n  const [age, setAge] = useState(30);\n  const adjust = useCallback((delta) =\u003e setAge((prev) =\u003e prev + delta), []);\n\n  return (\n    \u003cdiv\u003e\n      \u003ch1\u003e{name}\u003c/h1\u003e\n      \u003cp\u003e{age}\u003c/p\u003e\n      \u003cbutton onClick={() =\u003e adjust(-1)}\u003eBe younger\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e adjust(1)}\u003eBe older\u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n**After**\n\n```jsx\nimport { useAgent, useAgentState, useAgentTool } from \"react-agent-hooks\";\n\nexport function MyComponent() {\n  const agent = useAgent({ apiKey: \"******\" });\n  const [name, setName] = useAgentState(\"Name\", \"John Doe\");\n  const [age, setAge] = useAgentState(\"Age\", 30);\n  const adjust = useCallback((delta) =\u003e setAge((prev) =\u003e prev + delta), []);\n  useAgentTool(\"Change age\", z.number().describe(\"the delta of age change\"), adjust);\n\n  return (\n    \u003cdiv\u003e\n      \u003ch1\u003e{name}\u003c/h1\u003e\n      \u003cp\u003e{age}\u003c/p\u003e\n      \u003cbutton onClick={() =\u003e agent.run(\"be younger\")}\u003eBe younger\u003c/button\u003e\n      \u003cbutton onClick={() =\u003e agent.run(\"be older\")}\u003eBe older\u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz_small.svg)](https://stackblitz.com/edit/react-agentic-counter?file=src%2Fmain.jsx)\n\n## Get Started\n\n```sh\nnpm install react-agent-hooks\n```\n\n## Usage\n\n### Give Agent \"Eyes\" 👀\n\n```tsx\nimport { useAgentMemo } from \"react-agent-hooks\";\n\nfunction MyComponent() {\n  const [name, setName] = useState(\"John Doe\");\n  const [age, setAge] = useState(30);\n\n  // Describe a readable state to the Agent\n  useAgentMemo(\"User's profile\", () =\u003e ({ name, age }), [name, age]);\n\n  return (\n    \u003cdiv\u003e\n      \u003ch1\u003e{name}\u003c/h1\u003e\n      \u003cp\u003e{age}\u003c/p\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n### Give Agent \"Hands\" 👏\n\n```tsx\nimport {z} from \"zod\";\nimport { useAgentState, useAgentTool } from \"react-agent-hooks\";\n\nfunction MyComponent() {\n\n  // Describe a readable state to the Agent while exposing a setter function to developer\n  const [foodPreferences, setFoodPreferences] = useAgentState(\"food preference\", [\"Pizza\", \"Sushi\"]);\n\n  // Wrap the setter as a tool and describe it to the Agent\n  const addFoodPreference = useAgentTool(\"add-food-preference\", z.object(foodItems: z.array(z.string())), (foodItems) =\u003e {\n    setFoodPreferences((prev) =\u003e [...prev, ...foodItems]);\n  });\n  const removeFoodPreference = useAgentTool(\"remove-food-preference\", z.object(foodItems: z.array(z.string())), (foodItems) =\u003e {\n    setFoodPreferences((prev) =\u003e prev.filter((item) =\u003e !foodItems.includes(item)));\n  });\n\n  return \u003cul\u003e\n    {foodPreferences.map(item =\u003e \u003cli key={item}\u003e{item}\u003c/li\u003e)}\n    \u003c/ul\u003e\n}\n```\n\n### Run the Agent\n\n```tsx\nimport { useAgent } from \"react-agent-hooks\";\n\nfunction MyApp() {\n  // Run the Agent with a prompt\n  // Agent always sees the latest states from `useAgentState`, `useAgentMemo`, and can uses the latest tools from `useAgentTool`\n  const agent = useAgent({ apiKey: \"******\" });\n\n  // Call the Agent\n  const handleFormSubmit = (e) =\u003e {\n    e.preventDefault();\n    const input = e.target.elements[0].value;\n    agent.run(input);\n  };\n\n  return (\n    \u003cform onSubmit={handleFormSubmit}\u003e\n      \u003cinput type=\"text\" placeholder=\"Your request\" /\u003e\n      \u003cbutton onClick={handleRunAgent}\u003eAsk Agent\u003c/button\u003e\n    \u003c/form\u003e\n  );\n}\n```\n\n### Compose Agentic Application\n\nInside a component, use the `enabled` option to dynamically show/hide states and tools to the Agent.\n\n```tsx\nconst shouldShowFeature = true; // You can dynamically decide this value\nuseAgentMemo(\"User's profile\", () =\u003e ({ name, age }), [name, age], { enabled: shouldShowFeature });\nuseAgentState(\"some state\", { name: \"Some state\" }, { enabled: shouldShowFeature });\nuseAgentTool(\n  \"update state\",\n  z.object({ name: z.string() }),\n  (newState) =\u003e {\n    setSomeState(newState);\n  },\n  { enabled: shouldShowFeature },\n);\n```\n\nIn a component tree, use JSX to dynamically show/hide states and tools to the Agent.\n\n```tsx\nfunction ParentComponent() {\n  // A higher level component can dynamically decide what lower level states/tools are available\n  const = [shouldShowFeature, setShouldShowFeature] = useAgentState(\"toggle feature\", z.boolean(), true);\n\n  useAgentTool(\"toggle feature\", z.object({}), () =\u003e setShouldShowFeature(prev) =\u003e !prev);\n\n  return \u003cAppRoot\u003e{shouldShowFeatureB ? \u003cChildComponent /\u003e : null}\u003c/AppRoot\u003e;\n}\n\nfunction ChildComponent() {\n  // The state and tool will be available to the Agent only if the child component is rendered\n  useAgentState(\"some state\", { name: \"Some state\" });\n  useAgentTool(\"update state\", z.object({ name: z.string() }), (newState) =\u003e {\n    setSomeState(newState);\n  });\n\n  return \u003cdiv\u003e...\u003c/div\u003e;\n}\n```\n\n### Build a custom Agent\n\nAccess currently active states and tools with `useAgentContext` hook. Here is an example of building your own agent\n\n```tsx\nexport function useMyAgent() {\n  const openai = new OpenAI({ dangerouslyAllowBrowser: true, apiKey: \"******\" });\n  const agentContext = useAgentContext();\n\n  const run = async (prompt: string) =\u003e {\n    const task = openai.beta.chat.completions.runTools({\n      stream: true,\n      model: \"gpt-4.1\",\n      messages: [\n        {\n          role: \"system\",\n          content: `\nUser is interacting with a web app in the following state:\n\\`\\`\\`yaml\n${agentContext.stringifyStates()}\n\\`\\`\\`\n\nBased on user's instruction or goals, either answer user's question based on app state, or use one of the provided tools to update the state.\nShort verbal answer/confirmation in the end.\n          `.trim(),\n        },\n        {\n          role: \"user\",\n          content: prompt,\n        },\n      ],\n      tools: agentContext.getTools(),\n    });\n\n    return task;\n  };\n\n  return {\n    run,\n  };\n}\n```\n\n### Scale-up with Context\n\nThe `AgentContext` is an optional React Context to help you hierarchically organizing states and tools.\nThis prevents naming collisions and reduces agent confusion from too many similar states and tools.\n\n```tsx\nimport { AgentContext } from \"react-agent-hooks\";\n\nfunction MyApp() {\n  return (\n    \u003cAgentContext name=\"app root\"\u003e\n      \u003cAgentContext name=\"nav\"\u003e\n        \u003cNav /\u003e\n      \u003c/AgentContext\u003e\n      \u003cAgentContext name=\"content\"\u003e\n        \u003cheader\u003e\n          \u003cAgentContext name=\"header\"\u003e\n            \u003cHeaderContent /\u003e\n          \u003c/AgentContext\u003e\n        \u003c/header\u003e\n        \u003cmain\u003e\n          \u003cAgentContext name=\"main\"\u003e\n            \u003cMainContent /\u003e\n          \u003c/AgentContext\u003e\n        \u003c/main\u003e\n      \u003c/AgentContext\u003e\n    \u003c/AgentContext\u003e\n  );\n}\n\nfunction HeaderContent() {\n  // The Agent will see this state appear within the \"app root \u003e nav \u003e header\" context\n  const [someState, setSomeState] = useAgentState(\"some state\", { name: \"Some state\" });\n  return \u003cdiv\u003e...\u003c/div\u003e;\n}\n```\n\n## Future Work\n\nRender to MCP Server\n\n```tsx\nimport { renderToMCPServer } from \"react-agent-hooks\";\n\nfunction main() {\n  // Spin up an MCP server at port 3000.\n  // React Agent state -\u003e MCP resource and prompts\n  // React Agent tools -\u003e MCP tools\n  const server = renderToMCPServer(\u003cApp /\u003e).listen(3000);\n}\n```\n\nRender to llms.txt\n\n```tsx\nimport { renderToLlmsTxt } from \"react-agent-hooks\";\n\nfunction main() {\n  server.get(\"/llms.txt\", (req, res) =\u003e {\n    const userContext = req.query.userContext;\n    const llmsTxtContent = renderToLlmsTxt(\u003cApp context={userContext} /\u003e);\n    res.send(llmsTxtContent);\n  });\n}\n```\n\n## Reference\n\nBlog article: [React (hooks) is All You Need](https://stackdiver.com/posts/react-hooks-is-all-you-need/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchuanqisun%2Freact-agent-hooks","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchuanqisun%2Freact-agent-hooks","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchuanqisun%2Freact-agent-hooks/lists"}