{"id":343885,"url":"https://github.com/trojanowski/react-apollo-hooks","last_synced_at":"2026-01-12T02:46:39.316Z","repository":{"id":33214014,"uuid":"155170466","full_name":"trojanowski/react-apollo-hooks","owner":"trojanowski","description":"Use Apollo Client as React hooks","archived":false,"fork":false,"pushed_at":"2022-12-09T15:40:06.000Z","size":2154,"stargazers_count":2414,"open_issues_count":96,"forks_count":112,"subscribers_count":25,"default_branch":"master","last_synced_at":"2024-05-17T07:42:27.146Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","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/trojanowski.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","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":"2018-10-29T07:35:20.000Z","updated_at":"2024-05-16T17:25:04.000Z","dependencies_parsed_at":"2023-01-14T23:56:23.232Z","dependency_job_id":null,"html_url":"https://github.com/trojanowski/react-apollo-hooks","commit_stats":null,"previous_names":[],"tags_count":22,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trojanowski%2Freact-apollo-hooks","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trojanowski%2Freact-apollo-hooks/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trojanowski%2Freact-apollo-hooks/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trojanowski%2Freact-apollo-hooks/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/trojanowski","download_url":"https://codeload.github.com/trojanowski/react-apollo-hooks/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":215100127,"owners_count":15829027,"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":[],"created_at":"2024-01-07T12:47:11.485Z","updated_at":"2026-01-12T02:46:39.275Z","avatar_url":"https://github.com/trojanowski.png","language":"TypeScript","funding_links":[],"categories":["TypeScript","Packages"],"sub_categories":[],"readme":"# react-apollo-hooks\n\nThis library is deprecated. Please migrate to the \n[official React Apollo Hooks](https://www.npmjs.com/package/@apollo/react-hooks).\n\n---\n\nUse [Apollo Client](https://github.com/apollographql/apollo-client) as React\n[hooks](https://reactjs.org/docs/hooks-intro.html).\n\n[![CircleCI](https://circleci.com/gh/trojanowski/react-apollo-hooks.svg?style=svg)](https://circleci.com/gh/trojanowski/react-apollo-hooks)\n\n# Installation\n\n`npm install react-apollo-hooks`\n\nOr if using [yarn](https://yarnpkg.com/en/)\n\n\n`yarn add react-apollo-hooks`\n\n# Example\n\n\u003chttps://codesandbox.io/s/8819w85jn9\u003e is a port of Pupstagram sample app to\nreact-apollo-hooks.\n\n# API\n\n## ApolloProvider\n\nSimilar to\n[ApolloProvider from react-apollo](https://www.apollographql.com/docs/react/essentials/get-started.html#creating-provider).\nBoth packages can be used together, if you want to try out using hooks and\nretain `Query`, `Mutation`, `Subscription`, etc. HOCs from `react-apollo`\nwithout having to rewrite existing components throughout your app.\n\nIn order for this package to work, you need to wrap your component tree with\n`ApolloProvider` at an appropriate level, encapsulating all components which\nwill use hooks.\n\n### Standalone usage\n\nIf you would like to use this package standalone, this can be done with:\n\n```javascript\nimport React from 'react';\nimport { render } from 'react-dom';\n\nimport { ApolloProvider } from 'react-apollo-hooks';\n\nconst client = ... // create Apollo client\n\nconst App = () =\u003e (\n  \u003cApolloProvider client={client}\u003e\n    \u003cMyRootComponent /\u003e\n  \u003c/ApolloProvider\u003e\n);\n\nrender(\u003cApp /\u003e, document.getElementById('root'));\n```\n\n### Usage with react-apollo\n\nTo use with `react-apollo`'s `ApolloProvider` already present in your project:\n\n```javascript\nimport React from 'react';\nimport { render } from 'react-dom';\n\nimport { ApolloProvider } from 'react-apollo';\nimport { ApolloProvider as ApolloHooksProvider } from 'react-apollo-hooks';\n\nconst client = ... // create Apollo client\n\nconst App = () =\u003e (\n  \u003cApolloProvider client={client}\u003e\n    \u003cApolloHooksProvider client={client}\u003e\n      \u003cMyRootComponent /\u003e\n   \u003c/ApolloHooksProvider\u003e\n  \u003c/ApolloProvider\u003e\n);\n\nrender(\u003cApp /\u003e, document.getElementById('root'));\n```\n\n## useQuery\n\n```javascript\nimport gql from 'graphql-tag';\nimport { useQuery } from 'react-apollo-hooks';\n\nconst GET_DOGS = gql`\n  {\n    dogs {\n      id\n      breed\n    }\n  }\n`;\n\nconst Dogs = () =\u003e {\n  const { data, error, loading } = useQuery(GET_DOGS);\n  if (loading) {\n    return \u003cdiv\u003eLoading...\u003c/div\u003e;\n  };\n  if (error) {\n    return \u003cdiv\u003eError! {error.message}\u003c/div\u003e;\n  };\n\n  return (\n    \u003cul\u003e\n      {data.dogs.map(dog =\u003e (\n        \u003cli key={dog.id}\u003e{dog.breed}\u003c/li\u003e\n      ))}\n    \u003c/ul\u003e\n  );\n};\n\n```\n\n### Usage with Suspense (experimental)\n\nYou can use `useQuery` with [React Suspense](https://www.youtube.com/watch?v=6g3g0Q_XVb4)\nwith the `{ suspend: true }` option.\nPlease note that it's not yet recommended to use it in production. Please look\nat the [issue #69](https://github.com/trojanowski/react-apollo-hooks/issues/69)\nfor details.\n\nExample usage:\n\n```javascript\nimport gql from 'graphql-tag';\nimport React, { Suspense } from 'react';\nimport { useQuery } from 'react-apollo-hooks';\n\nconst GET_DOGS = gql`\n  {\n    dogs {\n      id\n      breed\n    }\n  }\n`;\n\nconst Dogs = () =\u003e {\n  const { data, error } = useQuery(GET_DOGS, { suspend: true });\n  if (error) {\n    return \u003cdiv\u003eError! {error.message}\u003c/div\u003e;\n  }\n\n  return (\n    \u003cul\u003e\n      {data.dogs.map(dog =\u003e (\n        \u003cli key={dog.id}\u003e{dog.breed}\u003c/li\u003e\n      ))}\n    \u003c/ul\u003e\n  );\n};\n\nconst MyComponent = () =\u003e (\n  \u003cSuspense fallback={\u003cdiv\u003eLoading...\u003c/div\u003e}\u003e\n    \u003cDogs /\u003e\n  \u003c/Suspense\u003e\n);\n```\n\nThere are known issues with suspense mode for `useQuery`:\n\n* only the `cache-first` fetch policy is supported ([#13](https://github.com/trojanowski/react-apollo-hooks/issues/13))\n* `networkStatus` returned by `useQuery` is undefined ([#68](https://github.com/trojanowski/react-apollo-hooks/pull/68))\n\n## useMutation\n\n```javascript\nimport gql from 'graphql-tag';\nimport { useMutation } from 'react-apollo-hooks';\n\nconst TOGGLE_LIKED_PHOTO = gql`\n  mutation toggleLikedPhoto($id: String!) {\n    toggleLikedPhoto(id: $id) @client\n  }\n`;\n\nconst DogWithLikes = ({ url, imageId, isLiked }) =\u003e {\n  const [toggleLike, { loading }] = useMutation(TOGGLE_LIKED_PHOTO, {\n    variables: { id: imageId },\n  });\n  return (\n    \u003cdiv\u003e\n      \u003cimg src={url} /\u003e\n      \u003cbutton onClick={toggleLike} disabled={loading}\u003e{isLiked ? 'Stop liking' : 'like'}\u003c/button\u003e\n    \u003c/div\u003e\n  );\n};\n```\n\nThe `useMutation` returns a tuple with mutation function first and the result of mutation execution in second. It's a similar signature you might know from official [Mutation component](https://www.apollographql.com/docs/react/essentials/mutations.html#errors) and the same behavior as well.\n\nYou can provide any\n[mutation options](https://www.apollographql.com/docs/react/api/apollo-client.html#ApolloClient.mutate)\nas an argument to the `useMutation` hook or to the function returned by it, e.\ng.:\n\n```javascript\nfunction AddTaskForm() {\n  const inputRef = useRef();\n  const [addTask] = useMutation(ADD_TASK_MUTATION, {\n    update: (proxy, mutationResult) =\u003e {\n      /* your custom update logic */\n    },\n    variables: {\n      text: inputRef.current.value,\n    },\n  });\n\n  return (\n    \u003cform\u003e\n      \u003cinput ref={inputRef} /\u003e\n      \u003cbutton onClick={addTask}\u003eAdd task\u003c/button\u003e\n    \u003c/form\u003e\n  );\n}\n```\n\nOr:\n\n```javascript\nfunction TasksWithMutation() {\n  const [toggleTask] = useMutation(TOGGLE_TASK_MUTATION);\n\n  return (\n    \u003cTaskList\n      onChange={task =\u003e toggleTask({ variables: { taskId: task.id } })}\n      tasks={data.tasks}\n    /\u003e\n  );\n}\n```\n\n## useSubscription\n\nIf you are just interested in the last subscription value sent by the\nserver (e. g. a global indicator showing how many new messages you have in an\ninstant messenger app) you can use `useSubscription` hook in this form:\n\n```javascript\nconst NEW_MESSAGES_COUNT_CHANGED_SUBSCRIPTION = gql`\n  subscription onNewMessagesCountChanged($repoFullName: String!) {\n    newMessagesCount\n  }\n`;\n\nconst NewMessagesIndicator = () =\u003e {\n  const { data, error, loading } = useSubscription(\n    NEW_MESSAGES_COUNT_CHANGED_SUBSCRIPTION\n  );\n\n  if (loading) {\n    return \u003cdiv\u003eLoading...\u003c/div\u003e;\n  };\n\n  if (error) {\n    return \u003cdiv\u003eError! {error.message}\u003c/div\u003e;\n  };\n\n  return \u003cdiv\u003e{data.newMessagesCount} new messages\u003c/div\u003e;\n}\n```\n\nFor more advanced use cases, e. g. when you'd like to show a notification\nto the user or modify the Apollo cache (e. g. you'd like to show a new comment\non a blog post page for a user visiting it just after it was created) you can\nuse the `onSubscriptionData` callback:\n\n```javascript\nconst { data, error, loading } = useSubscription(MY_SUBSCRIPTION, {\n  variables: {\n    // ...\n  },\n  onSubscriptionData: ({ client, subscriptionData }) =\u003e {\n    // Optional callback which provides you access to the new subscription\n    // data and the Apollo client. You can use methods of the client to update\n    // the Apollo cache:\n    // https://www.apollographql.com/docs/react/advanced/caching.html#direct\n  }\n  // ... rest options\n});\n```\n\nIn some cases you might want to subscribe only after you have all the information available, eg. only when user has selected necessary filters. Since hooks cannot be used conditionally, it would lead to unnecessary complicated patterns.\n\nInstead, you can use the `skip` option which turns the subsciption dormant until toggled again. It will also unsubscribe if there was any previous subscription active and throw away previous result.\n\n## useApolloClient\n\n```javascript\nconst MyComponent = () =\u003e {\n  const client = useApolloClient();\n  // now you have access to the Apollo client\n};\n```\n\n# Testing\n\nAn example showing how to test components using react-apollo-hooks:\n\u003chttps://github.com/trojanowski/react-apollo-hooks-sample-test\u003e\n\n# Server-side rendering\n\nreact-apollo-hooks supports server-side rendering with the `getMarkupFromTree`\nfunction. Example usage:\n\n```javascript\nimport express from 'express';\nimport { ApolloProvider, getMarkupFromTree } from 'react-apollo-hooks';\nimport { renderToString } from 'react-dom/server';\n\nconst HELLO_QUERY = gql`\n  query HelloQuery {\n    hello\n  }\n`;\n\nfunction Hello() {\n  const { data } = useQuery(HELLO_QUERY);\n\n  return \u003cp\u003e{data.message}\u003c/p\u003e;\n}\n\nconst app = express();\n\napp.get('/', async (req, res) =\u003e {\n  const client = createYourApolloClient();\n  const renderedHtml = await getMarkupFromTree({\n    renderFunction: renderToString,\n    tree: (\n      \u003cApolloProvider client={client}\u003e\n        \u003cHello /\u003e\n      \u003c/ApolloProvider\u003e\n    ),\n  });\n  res.send(renderedHtml);\n});\n```\n\n`getMarkupFromTree` supports `useQuery` hooks invoked in both suspense\nand non-suspense mode, but the [React.Suspense](https://reactjs.org/docs/react-api.html#reactsuspense)\ncomponent is not supported. You can use `unstable_SuspenseSSR` provided\nby this library instead:\n\n```javascript\nimport { unstable_SuspenseSSR as UnstableSuspenseSSR } from 'react-apollo-hooks';\n\nfunction MyComponent() {\n  return (\n    \u003cUnstableSuspenseSSR fallback={\u003cSpinner /\u003e}\u003e\n      \u003cdiv\u003e\n        \u003cComponentWithGraphqlQuery /\u003e\n      \u003c/div\u003e\n    \u003c/UnstableSuspenseSSR\u003e\n  );\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftrojanowski%2Freact-apollo-hooks","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftrojanowski%2Freact-apollo-hooks","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftrojanowski%2Freact-apollo-hooks/lists"}