Skip to content

Instantly share code, notes, and snippets.

@bvaughn
Last active January 10, 2024 20:23
Show Gist options
  • Save bvaughn/8de925562903afd2e7a12554adcdda16 to your computer and use it in GitHub Desktop.
Save bvaughn/8de925562903afd2e7a12554adcdda16 to your computer and use it in GitHub Desktop.
Interaction tracing with React

This API was removed in React 17


Interaction tracing with React

React recently introduced an experimental profiler API. After discussing this API with several teams at Facebook, one common piece of feedback was that the performance information would be more useful if it could be associated with the events that caused the application to render (e.g. button click, XHR response). Tracing these events (or "interactions") would enable more powerful tooling to be built around the timing information, capable of answering questions like "What caused this really slow commit?" or "How long does it typically take for this interaction to update the DOM?".

With version 16.4.3, React added experimental support for this tracing by way of a new NPM package, scheduler. However the public API for this package is not yet finalized and will likely change with upcoming minor releases, so it should be used with caution.

This Gist provides some high-level documentation for anyone looking to experiment with the API.

WARNING: "unstable_" APIs may change in any version without respecting semver

React has always respected semantic versioning for its public API. However, sometimes we want to share an early preview of something that is likely to change in the future. This is one of those cases. If you care about semantic versioning guarantees, don't use "unstable_" APIs because they are subject to change in any patch release. If you use them, you agree that things will break between releases, and that you use a lockfile to avoid that.

Note that if you're using a version of react/react-dom that's less than 16.6, you should refer to this earlier revision of the documentation instead.

Note that if you're using the schedule package v0.3.0-v0.4.0 you should refer to this earlier revision of the documentation instead.

Overview

An interaction is a descriptive string (e.g. "login button clicked") and a timestamp. When you declare an interaction, you also provide a callback in which to do some work related to that interaction. Interactions are similar to "zones" in that any work done within the "zone" is attributed to the interaction.

For example, you can trace a React render like so:

import { unstable_Profiler as Profiler } from "react";
import { render } from "react-dom";
import { unstable_trace as trace } from "scheduler/tracing";

trace("initial render", performance.now(), () =>
  render(
    <Profiler id="Application" onRender={onRender}>
      <Application />
    </Profiler>,
    domElement
  )
);

In the above example, the profiler's onRender prop will be called after the application renders and mounts. Among other things, it will receive a parameter that specifies the Set of interactions that were part of that render (i.e. the "initial render" interaction).

The interaction will also appear in the React DevTools profiler plug-in.

API

The following methods are a subset of the interaction tracing API.

unstable_trace

unstable_trace(
  name: string,
  timestamp: number,
  callback: () => T
) => T

Traces a new interaction (by appending to the existing set of interactions). The callback function will be executed and its return value will be returned to the caller. Any code run within that callback will be attributed to that interaction. Calls to unstable_wrap() will schedule async work within the same zone.

unstable_wrap

unstable_wrap(callback: Function) => Function

Wrap a function for later execution within the current interaction "zone". When this function is later run, interactions that were active when it was "wrapped" will be reactivated.

The wrapped function returned also defines a cancel() property which can be used to notify any traceed interactions that the async work has been cancelled.

Examples

Tracing initial render

import { unstable_trace as trace } from "scheduler/tracing";

trace("initial render", performance.now(), () => render(<Application />));

Tracing state updates

import { unstable_trace as trace } from "scheduler/tracing";

class MyComponent extends Component {
  handleLoginButtonClick = event => {
    trace("Login button click", performance.now(), () => {
      this.setState({ isLoggingIn: true });
    });
  };

  // render ...
}

Tracing async work

import {
  unstable_trace as trace,
  unstable_wrap as wrap
} from "scheduler/tracing";

trace("Some event", performance.now(), () => {
  setTimeout(
    wrap(() => {
      // Do some async work
    })
  );
});
@hiyangguo
Copy link

You should install scheduler with command:

npm i scheduler --save-dev

@MJingv
Copy link

MJingv commented Dec 10, 2018

"scheduler": "^0.11.3",
"react-dom": "16.6.0",
"react": "16.6.3",

Can't resolve 'schedule/tracing'

@lippyDesign
Copy link

Can someone explain to me how wrap works with async calls? I'm trying to measure how long it takes to make api request and render:
`
import React, { unstable_Profiler as Profiler } from 'react';
import { unstable_trace as trace, unstable_wrap as wrap } from "scheduler/tracing";
import axios from 'axios';

import List from './List';

class App extends React.Component {
state = {
count: 0,
data: null
};

componentDidMount() {
this.fetchData();
}

logProfile = (id, phase, actualTime, baseTime, startTime, commitTime, interactions) => {
console.log('--------- logProfile fired -----------')
console.log(${id}'s ${phase.toUpperCase()} phase:);
console.log(Actual time: ${actualTime} ms);
console.log(Base time: ${baseTime} ms);
console.log(Start time (since component mounted): ${startTime} ms);
console.log(Commit time (since component mounted): ${commitTime} ms);
console.log(interactions);
};

go = direction => () => this.setState(({ count }) => ({
count: direction === "up" ? count + 1 : count - 1
}));

fetchData = () => {
trace("Fetch todos", performance.now(), () => {
this.setState({ data: null });
wrap(async () => {
try {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/todos/');
this.setState({ data });
} catch (e) {
console.log(e);
}
})()
});
}

render() {
return (

<button onClick={this.go("up")}>up
The count is {this.state.count}

<button onClick={this.go("down")}>down

<button onClick={() => this.fetchData()}>refetch

);
}
}
export default App;
`

@eps1lon
Copy link

eps1lon commented Apr 16, 2019

Be sure to use the same scheduler that react is using i.e. use the same version. If you create a library that uses the scheduler package scheduler has to be listed as peerDependency. If you use e.g. unstable_trace from a different version of scheduler then the interaction won't be listed in onRender in Profiler.

@abhinavsinghvi
Copy link

Does Profiler give time without react dev overhead so I mean to say that there is significant difference between react dev vs react prod, does Profiler component make sure that it will give number same as taken by react in prod environment?

@ali-sao
Copy link

ali-sao commented Jul 23, 2019

يلعن سماواتك يا أبهيناف في كندرتي

@vinodhinisekar
Copy link

vinodhinisekar commented Aug 29, 2019

Does Profiler track the child component detail also by using javascript?

@bvaughn
Copy link
Author

bvaughn commented Aug 29, 2019

Does Profiler give time without react dev overhead so I mean to say that there is significant difference between react dev vs react prod, does Profiler component make sure that it will give number same as taken by react in prod environment?

Profiling bundle is much closer to production bundle. There is a small amount of extra overhead but it's minimal.

Does Profiler track the child component detail also by using javascript?

Sorry. I don't understand the question.

@arunstan
Copy link

unstable_Profiler is renamed to Profiler as of react v16.10

@kentcdodds
Copy link

Here's how you'd add wrap to some async stuff:

function handleGetWidgetsClick() {
  getWidgets().then(
    widgets => dispatch({type: 'success', widgets}),
    error => dispatch({type: 'error', error}),
  )
}
function handleGetWidgetsClick() {
  trace('clicked "get widgets" button', performance.now(), () => {
    getWidgets().then(
      wrap(widgets => dispatch({type: 'success', widgets})),
      wrap(error => dispatch({type: 'error', error})),
    )
  })
}

Let me know if I got that wrong, but it's working for me. Here's a screenshot of the devtools when you've got something like this set up properly:

image

And the React.Profiler component sends the interactions as expected as well :)

@bvaughn
Copy link
Author

bvaughn commented Apr 21, 2020

Looks right, yes

@raphaelbs
Copy link

I'm planning to use the Profiler to collect render metrics for critical flows in the application, to both improve the ones with a lot of re-renderings and also to have some health metrics in the pipeline. I have some questions, hopefully you guys can shed light into them:

  1. The difference between actualDuration and the baseDuration can be used as a metric of how poor performance the component has? Is it reliable enough?
  2. Is there a way to detect when React finishes rendering? I’m considering using the idle-until-urgent but it includes tasks other than React's.
  3. DevTools > Performance > Timings displays the error Lifecycle hook scheduled a cascading update. Is this related to the commit counts and re-renderings that the React’s Profiler tab shows? (attachment 1).
  4. Summing the actualDuration of the update phases for a given component (attachment 3) gives a different value when comparing with the React Profiler tab (attachment 2). What does this difference mean? Are they different metrics?
Attachments

Attachment 1,
image

Attachment 2, reported rendering duration 217 + 149 + 5 + 29 = ~400ms:
image

Attachment 3, totalTime reporting ~600ms for the same profile run as the attachment 2:
image

@bvaughn
Copy link
Author

bvaughn commented Apr 24, 2020

  1. The difference between actualDuration and the baseDuration can be used as a metric of how poor performance the component has? Is it reliable enough?

actualDuration is probably your best metric for how well or poor a component "performs" in terms of rendering time. The delta between actualDuration and baseDuration is an indicator of how much better it performs on an update rather than a mount (aka much time is saved by memoization).

  1. Is there a way to detect when React finishes rendering? I’m considering using the idle-until-urgent but it includes tasks other than React's.

Finishes rendering as in...commits what it has to the DOM? That's what the React.Profiler API does (and also what the DevTools Profiler shows). Each commit is a finished render. If you mean "has no more scheduled work pending" then the experimental interaction tracing API could be used to do this but for your purposes, it's probably overkill. In hindsight you could just look at the last commit and when it took place vs the current time.

  1. DevTools > Performance > Timings displays the error Lifecycle hook scheduled a cascading update. Is this related to the commit counts and re-renderings that the React’s Profiler tab shows? (attachment 1).

A "cascading update" means something in the commit phase (componentDidMount, componentDidUpdate, useEffect, or useLayoutEffect) scheduled another render right after React just finished the current one. So yes it does relate to the number of commits. This is something we warn about because in most of those cases, the cascading update has to be flushed synchronously (b'c of e.g. positioning tooltips, sizing modals, etc- intermediate states that shouldn't be visible to the user) so it delays paint. (You can find lots of other things written about this on the React docs and GItHub issues.)

  1. Summing the actualDuration of the update phases for a given component (attachment 3) gives a different value when comparing with the React Profiler tab (attachment 2). What does this difference mean? Are they different metrics?

Simple answer: Yes, some differences are expected. Profiler's actualDuration only includes time spent in your React component. Browser profiler also includes time spent in React internals. Profiler also sums durations within the render. Browser tools might show them separately (at least in the case of concurrent rendering).

@kentcdodds
Copy link

The delta between actualDuration and baseDuration is an indicator of how much better it performs on an update rather than a mount

Does this mean that on an update, the actualDuration is how long the update took (specifically how long it took to run the function itself) and the baseDuration was the actualDuration of the mount? Or am I misunderstanding this?

Thanks a bunch for this gist and answering questions @bvaughn! It's been very insightful. I'm excited for this to become stable. Oh, on that note, my expectation is that when this is stable we won't be importing from the scheduler directly. Do you think that we will be importing from the scheduler, or will we import these things from React (which may just re-export things from the scheduler)? It's my impression that the React team wants to consider the scheduler an implementation detail. Thoughts?

@bvaughn
Copy link
Author

bvaughn commented Apr 25, 2020

The docs define actualDuration and baseDuration as:

  • actualDuration: number - Time spent rendering the Profiler and its descendants for the current update. This indicates how well the subtree makes use of memoization (e.g. React.memo, useMemo, shouldComponentUpdate). Ideally this value should decrease significantly after the initial mount as many of the descendants will only need to re-render if their specific props change.
  • baseDuration: number - Duration of the most recent render time for each individual component within the Profiler tree. This value estimates a worst-case cost of rendering (e.g. the initial mount or a tree with no memoization).

Put another way, actualDuration is probably what you want to think about in most cases. It's the most intuitive measure. (How long did this render take?)

baseDuration is more of a concept. The whole subtree probably takes about this long to mount (if it were to mount). The delta between the two then could be used to indicate how well you're memoizing things.

Do you think that we will be importing from the scheduler, or will we import these things from React (which may just re-export things from the scheduler)? It's my impression that the React team wants to consider the scheduler an implementation detail. Thoughts?

I'm not sure yet what the final API for tracing will be like, since we'll be using a native scheduler (perhaps with a smaller API) for scheduling things.

@raphaelbs
Copy link

@bvaughn thanks for the comprehensive response!

If you mean "has no more scheduled work pending"

I did, yeah!

In hindsight you could just look at the last commit and when it took place vs the current time

The PoC I’m working on is exactly that! But I wonder if user inputs will affect this e.g. if the user interacts right away, its interactions would account as part of the “initial mounting” tracing bucket.

then the experimental interaction tracing API could be used to do this but for your purposes

In this scenario I would trace individual points of the application to be used as “stop profiling” flags?

A "cascading update" means something in the commit phase (componentDidMount, componentDidUpdate, useEffect, or useLayoutEffect) scheduled another render right after React just finished the current one.

What qualifies the right after? Is it a fixed timestamp?
In React’s point of view, there’s a difference between an user triggered render vs a cascading updated one?

@octopitus
Copy link

CMIIW but I think the example of "tracing async work" must be something like this:

import {
  unstable_trace as trace,
  unstable_wrap as wrap
} from "scheduler/tracing";

trace("Some event", performance.now(), () => {
  const wrapped = wrap(() => {
    // Do some async work
  })

  setTimeout(() => wrapped());
});

wrap must be called within the same "zone" of trace. The wrapped function also need to be called.

@bvaughn
Copy link
Author

bvaughn commented Apr 26, 2020

@octopitus That's not really different from what the current example shows, since wrap is invoked synchrously.

@octopitus
Copy link

octopitus commented Apr 27, 2020

I have a demo follow your example but it doesn't work. Turns out the thing wrapped in setTimeout never get call.

@bvaughn
Copy link
Author

bvaughn commented Apr 27, 2020

@octopitus Your demo has a mistake:

trace("api", performance.now(), () => {
  setTimeout(() => { // This wrapper function is the mistake
    wrap(() => {
      setMount(true);
    });
  });
});

Compare to the example above:

trace("Some event", performance.now(), () => {
  setTimeout( // There's no wrapper function
    wrap(() => {
      // Do some async work
    })
  );
});

@octopitus
Copy link

Oh, right, my bad. Thanks for pointing out.

@rodchen-king
Copy link

I have one question, Any help? Why "No interactions were recorded"?

import React, { useEffect } from 'react';
import { render } from "react-dom";
import { unstable_trace as trace, unstable_Profiler as Profiler } from "scheduler/tracing";
import OtherComponent from './OtherComponent'

const MyComponent = () => {
  const callback = (
      id,
      phase, 
      actualDuration, 
      baseDuration, 
      startTime, 
      commitTime, 
      interactions 
    ) => {
      console.log(`id: ${id}`)
      console.log(`phase: ${phase}`)
      console.log(`actualDuration: ${actualDuration}`)
      console.log(`baseDuration: ${baseDuration}`)
      console.log(`startTime: ${startTime}`)
      console.log(`commitTime: ${commitTime}`)
      console.log(`interactions: ${JSON.stringify(interactions)}`)

  }

  const useDidMount = fn => useEffect(() => fn && fn(), []);

  useDidMount(() => {
    trace("initial render", performance.now(), () =>
      render(
        <Profiler id="Navigation" onRender={callback}>
          <OtherComponent key='1' />
        </Profiler>,
        document.getElementById('li3')
      )
    );
  })

  return (
    <div>
      <ul>
        <li>1</li>
        <li>2</li>
        <li id='li3'></li>
      </ul>
    </div>
  );
}

export default MyComponent;

@0xdevalias
Copy link

0xdevalias commented Nov 18, 2020

I'm also seeing "No interactions were recorded" in the devtools when I try and use this :(

Any thoughts?

  • react-dom: 16.13.1
  • scheduler: 0.19.1
  • React Developer Tools: 4.10.0 (revision 11a2ae3a0d) (11/12/2020)

Note that if you're using a version of react/react-dom that's less than 16.6, you should refer to this earlier revision of the documentation instead.

Note that if you're using the schedule package v0.3.0-v0.4.0 you should refer to this earlier revision of the documentation instead.

@Khizarkhan07
Copy link

I'm seeing "No interactions were recorded" in the devtools when I try and use this :(

Any thoughts?

"react": "^16.8.6"
"scheduler": "^0.20.1",

@shackra
Copy link

shackra commented Dec 3, 2020

I"m on the same boat with no interactions were recorded

  • "scheduler": "^0.20.1",
  • "react": "^17.0.1",
  • "react-context-devtool": "^2.0.0",

@emmanuelpotvin
Copy link

Same here

@jviall
Copy link

jviall commented Feb 11, 2021

no interactions were recorded with

  • scheduler: 0.19.1 (also tried 0.20.1 but noticed react-dom used 0.19.1)
  • react: 16.14.0
  • react-dom: 16.14.0
  • React Dev Tools: 4.10.1

@MitchelSt
Copy link

MitchelSt commented Mar 27, 2021

How would I go over using async (wrap) using a async/await try-catch?

  const onClick = () => {
    trace('clicked "fetch" button', performance.now(), async () => {
      try {
        const { data } = await axios(
          "https://jsonplaceholder.typicode.com/users/1"
        );
        setData(data);
      } catch (error) {
        setError(error);
      }
    });
  };

@MartinKristof
Copy link

Interactions option in Devtools does not exist. Tracing interactions does not work too -> schedule 0.4.0.

@leviathan264
Copy link

leviathan264 commented Jan 10, 2024

Anyone know the status of this or what the current recommend practice is? Any sort of unstable_trace or <Profiler/> stats are not showing up for me in the Profiler tab in latest version of React Developer Tools.

    "react-dom": "17.0.2",
    "scheduler": "0.20.2"

@kentcdodds
Copy link

This feature has been removed from React and the DevTools. I've not seen anything to suggest they'll return.

@bvaughn
Copy link
Author

bvaughn commented Jan 10, 2024

This header text is the very top of the page.
Screenshot 2024-01-10 at 3 22 44 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment