Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useRollbar should return a memoized object #126

Open
FezVrasta opened this issue Apr 16, 2024 · 1 comment
Open

useRollbar should return a memoized object #126

FezVrasta opened this issue Apr 16, 2024 · 1 comment
Labels

Comments

@FezVrasta
Copy link

Currently useRollbar always returns a different identity anytime it's called, this makes it impossible to use it inside of memoized functions (useCallback).

@linear linear bot added the React label Apr 16, 2024
@sprice237
Copy link

sprice237 commented Oct 7, 2024

Here's what I've found:

import { useContext, useState } from 'react';
import { useRollbar, Context as RollbarContext } from '@rollbar/react';

export const RollbarNotifier = () => {
  const rollbar = useRollbar();
  const [prevRollbar, setPrevRollbar] = useState(rollbar);

  console.log('RollbarNotifier rendered');

  if (rollbar !== prevRollbar) {
    console.log('rollbar changed');
    setPrevRollbar(rollbar);
  }

  return null;
}

export const RollbarContextNotifier = () => {
  const rollbarContext = useContext(RollbarContext);
  const [prevRollbarContext, setPrevRollbarContext] = useState(rollbarContext);

  console.log('RollbarContextNotifier rendered');

  if (rollbarContext !== prevRollbarContext) {
    console.log('rollbarContext changed');
    setPrevRollbarContext(rollbarContext);
  }

  return null;
}

Running this, anytime RollbarWrapper renders, the underlying rollbar context is updated, but the return value of useRollbar is not. It appears that the underlying rollbar context is not memoized and is getting regenerated with every render. However, the return value of useRollbar pulls a field off of the underlying context (marked with a symbol called "RollbarInstance") which is created upon context creation and never changed. So, the return value of useRollbar should be referentially stable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants