fix(react): prevent duplicate spans in strict mode #2666
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Note: do not merge before #2661 gets merged.
Motivation
Currently if a user profiles a React component our
Profiler
component, and happens to be running in Strict Mode (https://reactjs.org/docs/strict-mode.html), each component creates two spans. It is important to note that Strict Mode runs in development mode only, so these issues are only in a development bundle environment.This occurs because in Strict Mode, certain functions are called multiple times:
In our case, it was calling the constructor twice (or useState twice in the hook), which was causing two spans to be created.
In a fresh install of create-react-app, Strict Mode is enabled by default. Therefore for many customers trying out AM for the first time, or playing around with
@sentry/react
, they will often encounter this problem.This PR aims to fix this.
Implementation
The way I get around this is by introducing a
cancelActivity
function to the tracing integration (9b36c14). By providing an activity ID, we can then prevent certain spans showing up in a transaction.
We can then track all activities generated by every profiled component, and if we recognize some as redundant, cancel the unnecessary activities. I have tried to leave detailed comments around this process, so read through that for more context on how this works.
Future
After this gets merged in, the React library is feature complete (for the time being).