{"id":20740930,"url":"https://github.com/rollbar/rollbar-react","last_synced_at":"2025-04-04T10:02:29.270Z","repository":{"id":38358283,"uuid":"356105000","full_name":"rollbar/rollbar-react","owner":"rollbar","description":"React features to enhance using Rollbar.js in React Applications","archived":false,"fork":false,"pushed_at":"2025-02-20T14:36:24.000Z","size":6285,"stargazers_count":44,"open_issues_count":20,"forks_count":12,"subscribers_count":22,"default_branch":"main","last_synced_at":"2025-03-28T09:01:42.552Z","etag":null,"topics":["error-monitoring","error-reporting","javascript","observability","react","reactjs","rollbar","typescript"],"latest_commit_sha":null,"homepage":"https://docs.rollbar.com/docs/react","language":"JavaScript","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/rollbar.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-04-09T02:08:33.000Z","updated_at":"2025-03-21T14:17:19.000Z","dependencies_parsed_at":"2023-02-18T08:31:39.490Z","dependency_job_id":"93a59541-32c9-41ac-b101-59bf0d1a218c","html_url":"https://github.com/rollbar/rollbar-react","commit_stats":{"total_commits":74,"total_committers":12,"mean_commits":6.166666666666667,"dds":0.7027027027027026,"last_synced_commit":"5c58a8522a0f20339de80979aa86dfe3e41c2759"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rollbar%2Frollbar-react","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rollbar%2Frollbar-react/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rollbar%2Frollbar-react/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rollbar%2Frollbar-react/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rollbar","download_url":"https://codeload.github.com/rollbar/rollbar-react/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247149505,"owners_count":20891954,"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":["error-monitoring","error-reporting","javascript","observability","react","reactjs","rollbar","typescript"],"created_at":"2024-11-17T06:31:21.809Z","updated_at":"2025-04-04T10:02:29.202Z","avatar_url":"https://github.com/rollbar.png","language":"JavaScript","readme":"\u003cp align=\"center\"\u003e\n  \u003cimg alt=\"rollbar-logo\" src=\"https://user-images.githubusercontent.com/3300063/207964480-54eda665-d6fe-4527-ba51-b0ab3f41f10b.png\" /\u003e\n\u003c/p\u003e\n\n\u003ch1 align=\"center\"\u003eRollbar React SDK\u003c/h1\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cstrong\u003eProactively discover, predict, and resolve errors in real-time with \u003ca href=\"https://rollbar.com\"\u003eRollbar’s\u003c/a\u003e error monitoring platform. \u003ca href=\"https://rollbar.com/signup/\"\u003eStart tracking errors today\u003c/a\u003e!\u003c/strong\u003e\n\u003c/p\u003e\n\n---\n\nReact features to enhance using Rollbar.js in React Applications.\n\nThis SDK provides a wrapper around the base [Rollbar.js] SDK in order to provide an\nSDK that matches the intention of how to build React Apps with a declarative API, features for the latest React API like\nhooks and ErrorBoundaries, as well as simplify using Rollbar within a React SPA.\n\n## Key benefits of using Rollbar React are:\n\n- **Telemetry:** The telemetry timeline provides a list of “breadcrumbs” events that can help developers understand and fix problems in their client-side javascript. \u003ca href=\"https://docs.rollbar.com/docs/rollbarjs-telemetry\"\u003eLearn more about telemetry\u003c/a\u003e.\n- **Automatic error grouping:** Rollbar aggregates Occurrences caused by the same error into Items that represent application issues. \u003ca href=\"https://docs.rollbar.com/docs/grouping-occurrences\"\u003eLearn more about reducing log noise\u003c/a\u003e.\n- **Advanced search:** Filter items by many different properties. \u003ca href=\"https://docs.rollbar.com/docs/search-items\"\u003eLearn more about search\u003c/a\u003e.\n- **Customizable notifications:** Rollbar supports several messaging and incident management tools where your team can get notified about errors and important events by real-time alerts. \u003ca href=\"https://docs.rollbar.com/docs/notifications\"\u003eLearn more about Rollbar notifications\u003c/a\u003e.\n\n### In Beta\n\nIt is currently in a public Beta release right now as we push towards a 1.0 release that will have all of the features\nwe want to provide full capability for using React SDK in your production apps. We expect a 1.0 release to come in the\nnext month.\n\n- [Key benefits of using Rollbar React are:](#key-benefits-of-using-rollbar-react-are)\n  - [In Beta](#in-beta)\n- [Setup Instructions](#setup-instructions)\n  - [Prerequisites](#prerequisites)\n  - [Install Rollbar React SDK](#install-rollbar-react-sdk)\n- [Usage and Reference](#usage-and-reference)\n  - [Simplest Usage Possible](#simplest-usage-possible)\n  - [Using with Next.js App Router](#using-with-nextjs-app-router)\n- [Components](#components)\n  - [`Provider` Component](#provider-component)\n    - [Configuration Only Usage](#configuration-only-usage)\n    - [Instance Usage](#instance-usage)\n    - [React Native Usage](#react-native-usage)\n  - [`ErrorBoundary` Component](#errorboundary-component)\n    - [Simple Usage](#simple-usage)\n    - [Pass `prop`s to control behavior](#pass-props-to-control-behavior)\n    - [Pass a Fallback UI](#pass-a-fallback-ui)\n  - [`RollbarContext` Component](#rollbarcontext-component)\n    - [Basic Usage](#basic-usage)\n    - [Using with React Router](#using-with-react-router)\n- [Functions](#functions)\n  - [`historyContext` to create `history.listener`](#historycontext-to-create-historylistener)\n    - [Basic `historyContext` usage](#basic-historycontext-usage)\n    - [Controlling `historyContext` behavior with options](#controlling-historycontext-behavior-with-options)\n- [Hooks](#hooks)\n  - [Reliance on `Provider`](#reliance-on-provider)\n  - [`useRollbar` hook](#userollbar-hook)\n  - [`useRollbarContext` hook](#userollbarcontext-hook)\n  - [`useRollbarPerson` hook](#userollbarperson-hook)\n  - [`useRollbarCaptureEvent` hook](#userollbarcaptureevent-hook)\n\n## Setup Instructions\n\n### Prerequisites\n\nThese instructions provide an addendum to the [Rollbar.js Setup Instructions].\n\nAfter following those 2 steps, you will be ready.\n\n### Install Rollbar React SDK\n\nTo install with `npm`:\n\n```shell\nnpm install @rollbar/react rollbar\n```\n\nTo install with `yarn`:\n\n```shell\nyarn add @rollbar/react rollbar\n```\n\nTo install by adding to `package.json`, add the following to your project's\n`package.json` file:\n\n```json\n  …\n  \"dependencies\": {\n    \"@rollbar/react\": \"^0.8.0\",\n    \"rollbar\": \"^2.24.0\",\n    …\n  }\n  …\n```\n\nthen run either using `npm` or `yarn` (or other package manager):\n\n```shell\nnpm install\n# OR\nyarn install\n```\n\n## Usage and Reference\n\nThe React SDK is very new and has not been given the full documentation treatment we expect to get from [Rollbar Docs],\nbut that will be coming shortly and a direct link will be put here for your reference.\n\nIn the meantime, the basic usage reference is available below.\n\n### Simplest Usage Possible\n\nTo get you started quickly, here is an example that will get you started right away by providing the easiest and simplest\nusage possible:\n\n```javascript\nimport React from 'react';\nimport { Provider, ErrorBoundary } from '@rollbar/react'; // \u003c-- Provider imports 'rollbar' for us\n\n// same configuration you would create for the Rollbar.js SDK\nconst rollbarConfig = {\n  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',\n  environment: 'production',\n};\n\nexport default function App() {\n  return (\n    {/* Provider instantiates Rollbar client instance handling any uncaught errors or unhandled promises in the browser */}\n    \u003cProvider config={rollbarConfig}\u003e\n      {/* ErrorBoundary catches all React errors in the tree below and logs them to Rollbar */}\n      \u003cErrorBoundary\u003e\n        // all other app providers and components - Rollbar will just work\n        …\n      \u003c/ErrorBoundary\u003e\n    \u003c/Provider\u003e\n  );\n};\n```\n\n### Using with Next.js App Router\n\nThe first step to using Rollbar with the Next.js App Router is to configure your Rollbar instance.\n\n```ts\nimport Rollbar from 'rollbar';\n\nconst baseConfig = {\n  captureUncaught: true,\n  captureUnhandledRejections: true,\n  environment: process.env.NODE_ENV,\n};\n\nexport const clientConfig = {\n  accessToken: process.env.NEXT_PUBLIC_POST_CLIENT_ITEM_TOKEN,\n  ...baseConfig,\n};\n\nexport const serverInstance = new Rollbar({\n  accessToken: process.env.POST_SERVER_ITEM_TOKEN,\n  ...baseConfig,\n});\n```\n\nWe suggest you create a single instance for use server side, to be certain there are not more than one, and a config to use in your client side components. React Server Components limit you to passing simple objects as props from Server Components to Client Components. The config object can be used by the Rollbar Provider to construct your Rollbar instance.\n\nThere's a fully functional [example](./examples/nextjs-approuter) that showcases the many ways in which you can integrate Rollbar into your modern web-app leveraging React Server Components and the Next.js App Router.\n\n## Components\n\nThe following components are available as named imports from `@rollbar/react`.\n\n### `Provider` Component\n\nThe `Provider` component is used to wrap your React App so an instance of Rollbar will be made available within your React tree.\n\nThis is a common pattern in React using a custom [React Context] that is available to the\n`Components` and `hooks` from this SDK library.\n\n#### Configuration Only Usage\n\nThe simplest way to use the `Provider` is to provide a configuration as the `config` prop which will instantiate an\ninstance of Rollbar for you and provide that to its child tree:\n\n```javascript\nimport React from 'react';\nimport { Provider } from '@rollbar/react';\n\n// same configuration you would create for the Rollbar.js SDK\nconst rollbarConfig = {\n  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',\n  environment: 'production',\n};\n\nexport function App(props) {\n  return \u003cProvider config={rollbarConfig}\u003e…\u003c/Provider\u003e;\n}\n```\n\n#### Instance Usage\n\nSometimes you may need to instantiate an instance of Rollbar before adding it to your App tree. In that case use the\n`instance` prop to pass it to the `Provider` like this:\n\n```javascript\nimport React from 'react';\nimport Rollbar from 'rollbar';\nimport { Provider } from '@rollbar/react';\n\n// same configuration you would create for the Rollbar.js SDK\nconst rollbarConfig = {\n  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',\n  environment: 'production',\n};\n\nconst rollbar = new Rollbar(rollbarConfig);\n\nexport function App(props) {\n  return \u003cProvider instance={rollbar}\u003e…\u003c/Provider\u003e;\n}\n```\n\nThis method will also work with the global Rollbar instance when using the `Rollbar.init(…)` method.\n\n#### React Native Usage\n\nRollbar provides a [React Native SDK] which also wraps the [Rollbar.js] to provide React Native capabilities based on\nthat specific environment.\n\nTo use the Rollbar React SDK with the [React Native SDK], pass the instance that it generates to the `Provider`'s\n`instance` prop, like this:\n\n```javascript\nimport React from 'react';\nimport { Client } from 'rollbar-react-native';\nimport { Provider } from '@rollbar/react';\n\nconst rollbarClient = new Client('POST_CLIENT_ITEM_ACCESS_TOKEN');\n\nexport function App(props) {\n  return \u003cProvider instance={rollbarClient.rollbar}\u003e…\u003c/Provider\u003e;\n}\n```\n\n### `ErrorBoundary` Component\n\nRollbar's React SDK provides a new `ErrorBoundary` component which implements the interface for React's [Error Boundaries]\nintroduced in React 16.\n\nThe `ErrorBoundary` is used to wrap any tree or subtree in your React App to catch React Errors and log them to Rollbar\nautomatically.\n\nThe `ErrorBoundary` relies on the [`Provider`] above for the instance of Rollbar, so it will utilize\nwhatever configuration has been provided.\n\n#### Simple Usage\n\nYou can add an `ErrorBoundary` component to the top of your tree right after the [`Provider`] with no additional props\nand it will just work:\n\n```javascript\nimport React from 'react';\nimport { Provider, ErrorBoundary } from '@rollbar/react';\n\n// same configuration you would create for the Rollbar.js SDK\nconst rollbarConfig = {\n  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',\n  environment: 'production',\n};\n\nexport function App(props) {\n  return (\n    \u003cProvider config={rollbarConfig}\u003e\n      \u003cErrorBoundary\u003e…\u003c/ErrorBoundary\u003e\n    \u003c/Provider\u003e\n  );\n}\n```\n\n#### Pass `prop`s to control behavior\n\nThe `ErrorBoundary` provides several `prop`s that allow customizing the behavior of how it will report errors to\n[Rollbar].\n\nThese `prop`s take either a value or a function that will be invoked with the `error` and `info` from the [Error Boundaries]\nAPI's `componentDidCatch` method (i.e. signature is `(error, info)`).\n\n```javascript\nimport React from 'react';\nimport { Provider, ErrorBoundary, LEVEL_WARN } from '@rollbar/react';\n\n// same configuration you would create for the Rollbar.js SDK\nconst rollbarConfig = {\n  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',\n  environment: 'production',\n};\n\nexport function App(props) {\n  return (\n    \u003cProvider config={rollbarConfig}\u003e\n      \u003cErrorBoundary\n        level={LEVEL_WARN}\n        errorMessage=\"Error in React render\"\n        extra={(error, info) =\u003e\n          info.componentStack.includes('Experimental')\n            ? { experiment: true }\n            : {}\n        }\n      \u003e\n        …\n      \u003c/ErrorBoundary\u003e\n    \u003c/Provider\u003e\n  );\n}\n```\n\n#### Pass a Fallback UI\n\nYou may also include a Fallback UI to render when the error occurs so that the User does not experience a broken/blank\nUI caused during the render cycle of React.\n\nIt can accept a value that is a React Component\n\n```javascript\nimport React from 'react';\nimport { Provider, ErrorBoundary, LEVEL_WARN } from '@rollbar/react';\n\n// same configuration you would create for the Rollbar.js SDK\nconst rollbarConfig = {\n  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',\n  environment: 'production',\n};\n\nconst ErrorDisplay = (\n  { error, resetError }, // \u003c-- props passed to fallbackUI component\n) =\u003e (\n  \u003cdiv\u003e\n    \u003ch1\u003eA following error has occured:\u003c/h1\u003e\n    \u003cp\u003e{error.toString()}\u003c/p\u003e\n  \u003c/div\u003e\n);\n\nexport function App(props) {\n  return (\n    \u003cProvider config={rollbarConfig}\u003e\n      \u003cErrorBoundary level={LEVEL_WARN} fallbackUI={ErrorDisplay}\u003e\n        …\n      \u003c/ErrorBoundary\u003e\n    \u003c/Provider\u003e\n  );\n}\n```\n\n### `RollbarContext` Component\n\nUse the `RollbarContext` component to declaratively set the `context` value used by [Rollbar.js] when it's sending any\nmessages to [Rollbar].\n\nThis works for your `ErrorBoundary` from above or any other log or message sent to [Rollbar] while the `RollbarContext`\nis mounted on the tree.\n\nLike `ErrorBoundary` above, `RollbarContext` relies on a [`Provider`] for an instance of a [Rollbar.js] client.\n\n#### Basic Usage\n\nTo use the `RollbarContext` you must provide the `context` prop, a `String` that is used to set the context used by\n[Rollbar.js] to the value while mounted.\n\n```javascript\nimport React from 'react';\nimport { RollbarContext } from '@rollbar/react';\n\nfunction HomePage() {\n  return \u003cRollbarContext context=\"home\"\u003e…\u003c/RollbarContext\u003e;\n}\n```\n\n#### Using with React Router\n\nIt's useful to set the `context` in [Rollbar] associated with areas of your application. On the server it's usually\nset when a specific page is requested. For SPAs like React Apps, using `RollbarContext` with your Router is one way\nto achieve the same result.\n\nHere is an example of using `RollbarContext` with [React Router] if you have a top level set of routes:\n\n```javascript\nimport React from 'react';\nimport { Router, Switch, Route } from 'react-router-dom';\nimport { RollbarContext } from '@rollbar/react';\nimport { About, ContactDetails, ContactsList } from './pages';\n\nconst Routes = () =\u003e (\n  \u003cRouter\u003e\n    \u003cSwitch\u003e\n      \u003cRoute path=\"/about\"\u003e\n        \u003cRollbarContext context=\"/about\"\u003e\n          \u003cAbout /\u003e\n        \u003c/RollbarContext\u003e\n      \u003c/Route\u003e\n      \u003cRoute path=\"/contacts/:id\"\u003e\n        \u003cRollbarContext context=\"contacts/details\"\u003e\n          \u003cContactDetails /\u003e\n        \u003c/RollbarContext\u003e\n      \u003c/Route\u003e\n      \u003cRoute path=\"/contacts\"\u003e\n        \u003cRollbarContext context=\"contacts\"\u003e\n          \u003cContactsList /\u003e\n        \u003c/RollbarContext\u003e\n      \u003c/Route\u003e\n    \u003c/Switch\u003e\n  \u003c/Router\u003e\n);\n\nexport default Routes;\n```\n\nHere's another example of using `RollbarContext` within a component that manages its own route:\n\n```javascript\nimport React from 'react';\nimport { Route } from 'react-router-dom';\nimport { RollbarContext } from '@rollbar/react';\n\nexport default function About(props) {\n  return (\n    \u003cRoute path=\"/about\"\u003e\n      \u003cRollbarContext context=\"/about\"\u003e…\u003c/RollbarContext\u003e\n    \u003c/Route\u003e\n  );\n}\n```\n\n## Functions\n\nThe following functions are available as named imports from `@rollbar/react`.\n\n### `historyContext` to create `history.listener`\n\nA lot of SPAs and React Apps will use the [history] package to handle browser history. The\n`historyContext` function is a helper that creates a valid listener function to receive\nhistory changes and use those to change the [Rollbar.js] context.\n\n`historyContext` is a factory function used to create a proper `history.listen` callback\nthat will work for v4 and v5 of the [history] package.\n\n#### Basic `historyContext` usage\n\nThe `historyContext` factory function requires an instance of [Rollbar.js] to wrap in order\nto create the listener callback function.\n\nBy default, if no options (see below) are provided, all history updates will update the `context` for [Rollbar] using the\n`location.pathname` as the value.\n\n```javascript\nimport Rollbar from 'rollbar';\nimport { createBrowserHistory } from 'history';\nimport { Provider } from '@rollbar/react';\n\n// same configuration you would create for the Rollbar.js SDK\nconst rollbarConfig = {\n  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',\n  environment: 'production',\n};\n\nconst rollbar = new Rollbar(rollbarConfig);\n\nconst history = createBrowserHistory();\n\nhistory.listen(historyContext(rollbar));\n```\n\n#### Controlling `historyContext` behavior with options\n\nThe `historyContext` factory function accepts `options` as a 2nd argument that allow you to control the behavior\nof how and when the `context` will be set for the [Rollbar.js] client.\n\nUse the `formatter` option to provide a function that will receive the `history` change event and return a `String`\nthat you would like to be set as the `context` for [Rollbar].\n\nThe signature is `formatter(location, action): String` where `location` is [history.location] and `action` is [history.action].\n\nThe other option is `filter` which you can provide to tell the `historyContext` listener you create to control\nwhich history updates will change the `context` for [Rollbar]. All truthy values will tell the listener to make\nthe change. Any falsy values will skip the update.\n\nThe signature is `filter(location, action): Boolean` where `location` is [history.location] and `action` is [history.action].\n\nHere's an example of using both:\n\n```javascript\nimport Rollbar from 'rollbar';\nimport { createBrowserHistory } from 'history';\nimport { Provider } from '@rollbar/react';\n\n// same configuration you would create for the Rollbar.js SDK\nconst rollbarConfig = {\n  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',\n  environment: 'production',\n};\n\nconst rollbar = new Rollbar(rollbarConfig);\n\nconst ROUTE_PARAMS_RE = /\\/\\d+/g;\n\nconst historyListener = historyContext(rollbar, {\n  // optional: default uses location.pathname\n  formatter: (location, action) =\u003e\n    location.pathname.replace(ROUTE_PARAMS_RE, ''),\n  // optional: true return sets Rollbar context\n  filter: (location, action) =\u003e !location.pathname.includes('admin'),\n});\nconst unlisten = history.listen(historyListener);\n```\n\n## Hooks\n\nThe following hooks are available as named imports from `@rollbar/react` for use in [Functional Components] making use of the\n[React Hooks API] introduced in React 16.8.\n\n### Reliance on `Provider`\n\nAll of these hooks below require there to be a [`Provider`] in the React Tree as an ancestor to the component using the hook.\n\n### `useRollbar` hook\n\nTo consume the [Rollbar.js] instance directly from the [`Provider`] in your React Tree and make use of the client API within\nyour [Functional Component], use the `useRollbar` hook which will return the instance from the currently scoped [React Context].\n\nHere is a basic example:\n\n```javascript\nimport { useRollbar } from '@rollbar/react';\n\nfunction ContactDetails({ contactId }) {\n  const rollbar = useRollbar(); // \u003c-- must have parent Provider\n  const [contact, setContact] = useState();\n\n  useEffect(async () =\u003e {\n    try {\n      const { data } = await getContactFromApi(contactId);\n      setContact(data.contact);\n    } catch (error) {\n      rollbar.error('Error fetching contact', error, { contactId });\n    }\n  }, [contactId]);\n\n  return \u003cdiv\u003e…\u003c/div\u003e;\n}\n```\n\n### `useRollbarContext` hook\n\nAs an alternative to the [`RollbarContext`] component, you can use the `useRollbarContext` hook in your [Functional Component]\nto set the `context` in the [Rollbar.js] client provided by the [`Provider`] above in the React Tree.\n\nHere's an example of using it in several components:\n\n```javascript\n// src/pages/HomePage.js\nimport { useRollbarContext } from '@rollbar/react';\n\nfunction HomePage(props) {\n  useRollbarContext('home#index');\n\n  return \u003cdiv\u003e…\u003c/div\u003e;\n}\n\n// src/pages/UsersPage.js\nimport { useRollbarContext } from '@rollbar/react';\nimport UserTable from '../components/users/UserTable';\n\nfunction UsersPage(props) {\n  useRollbarContext('users#list');\n\n  return \u003cUserTable data={props.users} /\u003e;\n}\n\n// src/pages/UserDetailsPage.js\nimport { useRollbarContext } from '@rollbar/react';\nimport UserDetails from '../components/users/UserDetails';\n\nfunction UserDetailsPage(props) {\n  useRollbarContext('users#details');\n\n  return \u003cUserDetails user={props.user} /\u003e;\n}\n```\n\n### `useRollbarPerson` hook\n\nIt's very usefull in [Rollbar] to log the identity of a person or user using your App for 2 major reasons:\n\n1. It allows you to know exactly who has been affected by an item or error in your App\n2. It allows [Rollbar] to tell you the impact a given item or error is having on your users\n\nTo make it convenient and easy to set the identity of a person in your React App, the `@rollbar/react` package\nhas the `userRollbarPerson` hook.\n\nTo use it, simply pass an `Object` that has keys and values used to identify an individual user of your App,\nand for any future events or messages logged to [Rollbar] will include that person data attached to the log.\n\nHere is a simple example of using it once the current user has been determined:\n\n```javascript\nimport { useState } from 'react';\nimport { useRollbarPerson } from '@rollbar/react';\nimport LoggedInHome from './LoggedInHome';\nimport LoggedOutHome from './LoggedOutHome';\n\nfunction Home() {\n  const [currentUser, setCurrentUser] = useState();\n  useRollbarPerson(currentUser);\n\n  useEffect(() =\u003e {\n    (async () =\u003e {\n      const user = await Auth.getCurrentUser();\n      setCurrentUser(user);\n    })();\n  });\n\n  if (currentUser != null) {\n    return \u003cLoggedInHome /\u003e;\n  }\n\n  return \u003cLoggedOutHome /\u003e;\n}\n```\n\n### `useRollbarCaptureEvent` hook\n\n[Rollbar.js] already provides automated [Telemetry] with the default configuration `autoInstrument: true` in the client\nwhich will capture useful telemetry events and data for you.\n\nTo provide more breadcrumbs useful for identifying the cause of an item or error, you can add your own capture events\nthat will be included in the [Telemetry] of an item in [Rollbar] with the `useRollbarCaptureEvent` hook.\n\nThe `useRollbarCaptureEvent` hook is designed to capture a new event in your [Functional Component] any time the\n`metadata` or `level` you provide to the hook changes. On rerenders, no event is captured if there is not a change\nto the references provided to those 2 arguments (utilizing the `dependencies` array arg underneath within the call to\nthe built-in React `useEffect` hook).\n\nHere is an example of using `useRollbarCaptureEvent` in the render cycle of a [Functional Component] to send a telemetry\nevent related to the data that will be rendered in the component\n\n```javascript\nimport { useEffect, useState } from 'react';\nimport { useRollbar, useRollbarCaptureEvent, LEVEL_INFO } from '@rollbar/react';\n\nfunction BookDetails({ bookId }) {\n  const rollbar = useRollbar(); // \u003c-- must have ancestor Provider, same with useRollbarCaptureEvent\n  const [book, setBook] = useState();\n\n  useEffect(async () =\u003e {\n    try {\n      const { data } = await getBook(bookId);\n      setBook(data.book);\n    } catch (error) {\n      rollbar.error('Error fetching book', error, { bookId }); // \u003c-- use rollbar to log errors as normal\n    }\n  }, [bookId]);\n\n  useRollbarCaptureEvent(book, LEVEL_INFO); // \u003c-- only fires when book changes\n\n  return \u003cdiv\u003e…\u003c/div\u003e;\n}\n```\n\n[rollbar]: https://rollbar.com\n[rollbar docs]: https://docs.rollbar.com\n[rollbar.js]: https://github.com/rollbar/rollbar.js\n[rollbar.js setup instructions]: https://github.com/rollbar/rollbar.js/#setup-instructions\n[react native sdk]: https://github.com/rollbar/rollbar-react-native\n[telemetry]: https://docs.rollbar.com/docs/rollbarjs-telemetry\n[`provider`]: #provider-component\n[`errorboundary`]: #errorboundary-component\n[`rollbarcontext`]: #rollbarcontext-component\n[functional components]: https://reactjs.org/docs/components-and-props.html#function-and-class-components\n[react context]: https://reactjs.org/docs/context.html\n[error boundaries]: https://reactjs.org/docs/error-boundaries.html\n[react hooks api]: https://reactjs.org/docs/hooks-intro.html\n[history]: https://www.npmjs.com/package/history\n[history.location]: https://github.com/ReactTraining/history/blob/master/docs/api-reference.md#location\n[history.action]: https://github.com/ReactTraining/history/blob/master/docs/api-reference.md#action\n[1]: https://docs.github.com/en/packages/guides/configuring-npm-for-use-with-github-packages#installing-a-package\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frollbar%2Frollbar-react","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frollbar%2Frollbar-react","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frollbar%2Frollbar-react/lists"}