{"id":13624636,"url":"https://github.com/relay-tools/relay-hooks","last_synced_at":"2025-04-13T08:51:55.424Z","repository":{"id":34889550,"uuid":"187370162","full_name":"relay-tools/relay-hooks","owner":"relay-tools","description":"Use Relay as React hooks","archived":false,"fork":false,"pushed_at":"2024-11-26T11:50:49.000Z","size":3548,"stargazers_count":543,"open_issues_count":16,"forks_count":56,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-03-23T02:29:44.140Z","etag":null,"topics":["graphql","hooks","react","react-hooks","refetch","relay-hooks","relay-modern","ssr","suspense","usefragment","usemutation","usequery"],"latest_commit_sha":null,"homepage":"https://relay-tools.github.io/relay-hooks/docs/relay-hooks.html","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/relay-tools.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","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},"funding":{"github":["morrys"],"custom":"https://www.paypal.me/m0rrys"}},"created_at":"2019-05-18T14:51:09.000Z","updated_at":"2024-12-15T23:51:04.000Z","dependencies_parsed_at":"2023-02-17T18:01:12.301Z","dependency_job_id":"d6b4de34-27c2-41a2-8606-10e3a9f9acbc","html_url":"https://github.com/relay-tools/relay-hooks","commit_stats":{"total_commits":510,"total_committers":26,"mean_commits":"19.615384615384617","dds":"0.21568627450980393","last_synced_commit":"333d4380c35887d78aa4c8187543086b8177fc56"},"previous_names":[],"tags_count":42,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/relay-tools%2Frelay-hooks","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/relay-tools%2Frelay-hooks/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/relay-tools%2Frelay-hooks/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/relay-tools%2Frelay-hooks/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/relay-tools","download_url":"https://codeload.github.com/relay-tools/relay-hooks/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246273531,"owners_count":20750906,"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":["graphql","hooks","react","react-hooks","refetch","relay-hooks","relay-modern","ssr","suspense","usefragment","usemutation","usequery"],"created_at":"2024-08-01T21:01:44.490Z","updated_at":"2025-03-30T04:02:04.584Z","avatar_url":"https://github.com/relay-tools.png","language":"TypeScript","funding_links":["https://github.com/sponsors/morrys","https://www.paypal.me/m0rrys"],"categories":["TypeScript"],"sub_categories":[],"readme":"# relay-hooks \n![](https://github.com/relay-tools/relay-hooks/workflows/Build/badge.svg) \n[![npm](https://img.shields.io/npm/v/relay-hooks.svg)](https://www.npmjs.com/package/relay-hooks)\n[![npm downloads](https://img.shields.io/npm/dm/relay-hooks.svg)](https://www.npmjs.com/package/relay-hooks)\n\nUse Relay as React hooks\n\n## Installation\n\nInstall react-relay and relay-hooks using yarn or npm:\n\n```\nyarn add react-relay relay-hooks\n```\n\n## Contributing\n\n* **Give a star** to the repository and **share it**, you will **help** the **project** and the **people** who will find it useful\n\n* **Create issues**, your **questions** are a **valuable help**\n\n* **PRs are welcome**, but it is always **better to open the issue first** so as to **help** me and other people **evaluating it**\n\n* **Please sponsor me**\n\n### relay-hooks\n\nThe initial purpose of the library was to provide the ability to use all react-relay HOCs as react hooks and to implement the store-or-network and store-only policies used by the [react-relay-offline](https://github.com/morrys/react-relay-offline) library to manage offline relay applications\n\nAfter Relay's core team shared information about the the initial differences in the issue https://github.com/relay-tools/relay-hooks/issues/5, all the necessary changes were made in order to make relay-hooks as close as possible to their specifications.\n\n* current differences with upcoming Relay Hooks in react-relay\n\n  * **useLazyLoadQuery**: returns a *single* data object with the query's data, and nothing else.\n  * **useFragment**: in relay-hooks it is called useSuspenseFragment\n\n* what's more in relay-hooks\n\n  * **useQuery**: it is the same as `useLazyLoadQuery` but does not use suspense, it allows you to use hooks without having to migrate the application in concurrent mode and its return is the same as the QueryRenderer HOC\n  * **conditional useQuery \u0026 useLazyLoadQuery**: added `skip`: [Optional] If skip is true, the query will be skipped entirely\n  * **observe the execution of the query in the network in useQuery \u0026 useLazyLoadQuery**: added `onComplete`: [Optional] Function that will be called whenever the fetch request has completed\n\n* why use relay-hooks?\n\nIt is a stable library and none of its dependencies are experimental and it allows you to immediately use react hooks with relay-runtime and it is designed for easy migration to react-relay hooks.\n\nIt is a light library and compatible with react-relay\n\n## RelayEnvironmentProvider\n\nSince queries with `useQuery` no longer set context, we will expose a new `RelayEnvironmentProvider` component that takes an `environment` and sets it in context; \nvariables will no longer be part of context. \nA `RelayEnvironmentProvider` should be rendered once at the root of the app, and multiple useQuery's can be rendered under this environment provider.\n\n```ts\nimport { RelayEnvironmentProvider } from 'relay-hooks';\n\nReactDOM.render(\n  \u003cRelayEnvironmentProvider environment={modernEnvironment}\u003e\n    \u003cAppTodo/\u003e\n  \u003c/RelayEnvironmentProvider\u003e,\n  rootElement,\n);\n```\n\n## useQuery\n\n`useQuery` does not take an environment as an argument. Instead, it reads the environment set in the context; this also implies that it does not set any React context.\nIn addition to `query` (first argument) and `variables` (second argument), `useQuery` accepts a third argument `options`. \n\n**options**\n\n`fetchPolicy`: determine whether it should use data cached in the Relay store and whether to send a network request. The options are:\n  * `store-or-network` (default): Reuse data cached in the store; if the whole query is cached, skip the network request\n  * `store-and-network`: Reuse data cached in the store; always send a network request.\n  * `network-only`: Don't reuse data cached in the store; always send a network request. (This is the default behavior of Relay's existing `QueryRenderer`.)\n  * `store-only`: Reuse data cached in the store; never send a network request.\n\n`fetchKey`: [Optional] A fetchKey can be passed to force a refetch of the current query and variables when the component re-renders, even if the variables didn't change, or even if the component isn't remounted (similarly to how passing a different key to a React component will cause it to remount). If the fetchKey is different from the one used in the previous render, the current query and variables will be refetched.\n\n`networkCacheConfig`: [Optional] Object containing cache config options for the network layer. Note the the network layer may contain an additional query response cache which will reuse network responses for identical queries. If you want to bypass this cache completely, pass {force: true} as the value for this option.\n\n`skip`: [Optional] If skip is true, the query will be skipped entirely.\n\n`onComplete`: [Optional] Function that will be called whenever the fetch request has completed\n\n```ts\nimport { useQuery, graphql } from 'relay-hooks';\n\nconst query = graphql`\n  query appQuery($userId: String) {\n    user(id: $userId) {\n      ...TodoApp_user\n    }\n  }\n`;\n\nconst variables = {\n  userId: 'me',\n}; \n\nconst options = {\n  fetchPolicy: 'store-or-network', //default\n  networkCacheConfig: undefined,\n}\n\nconst AppTodo = function (appProps)  {\n  const {data, error, retry, isLoading} = useQuery(query, variables, options);\n\n  if (data \u0026\u0026 data.user) {\n    return \u003cTodoApp user={data.user} /\u003e;\n  } else if (error) {\n    return \u003cdiv\u003e{error.message}\u003c/div\u003e;\n  }\n  return \u003cdiv\u003eloading\u003c/div\u003e;\n}\n```\n\n## useLazyLoadQuery\n\nsame to useQuery\n\n```ts\nimport * as React from 'react';\nimport { useQuery, graphql, RelayEnvironmentProvider } from 'relay-hooks';\n\nconst query = graphql`\n  query appQuery($userId: String) {\n    user(id: $userId) {\n      ...TodoApp_user\n    }\n  }\n`;\n\nclass ErrorBoundary extends React.Component {\n  state = { error: null };\n  \n  componentDidCatch(error) {\n    this.setState({ error });\n  }\n\n  render() {\n    const { children, fallback } = this.props;\n    const { error } = this.state;\n    if (error) {\n      return React.createElement(fallback, { error });\n    }\n    return children;\n  }\n}\n\nconst variables = {\n  userId: 'me',\n}; \n\nconst options = {\n  fetchPolicy: 'store-or-network', //default\n  networkCacheConfig: undefined,\n}\n\n\nconst AppTodo = function (appProps) {\n  const {data} = useLazyLoadQuery(query, variables, options);\n  return \u003cTodoApp user={data.user} /\u003e;\n}\n\n\nconst App = (\n  \u003cRelayEnvironmentProvider environment={modernEnvironment}\u003e\n    \u003cErrorBoundary fallback={({ error }) =\u003e `Error: ${error.message + ': ' + error.stack}`}\u003e\n      \u003cReact.Suspense fallback={\u003cdiv\u003eloading suspense\u003c/div\u003e}\u003e\n        \u003cAppTodo /\u003e\n      \u003c/React.Suspense\u003e\n    \u003c/ErrorBoundary\u003e\n  \u003c/RelayEnvironmentProvider\u003e\n);\n```\n\n## useFragment\n\n[See useFragment.md](./docs/useFragment.md)\n\n## useRefetchable\n\n[See useRefetchable.md](./docs/useRefetchable.md)\n\n## usePagination\n\n[See usePagination.md](./docs/usePagination.md)\n\n## useMutation\n\n[See useMutation.md](./docs/useMutation.md)\n\n## useSubscription\n\n[See useSubscription.md](./docs/useSubscription.md)\n\n## usePreloadedQuery\n\n[See usePreloadedQuery.md](./docs/usePreloadedQuery.md)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frelay-tools%2Frelay-hooks","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frelay-tools%2Frelay-hooks","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frelay-tools%2Frelay-hooks/lists"}