rollbar-react
rollbar-react copied to clipboard
useRollbar should return a memoized object
Currently useRollbar always returns a different identity anytime it's called, this makes it impossible to use it inside of memoized functions (useCallback).
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.