惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
V
Visual Studio Blog
F
Full Disclosure
B
Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
L
Lohrmann on Cybersecurity
月光博客
月光博客
I
Intezer
博客园 - 三生石上(FineUI控件)
Hacker News - Newest:
Hacker News - Newest: "LLM"
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园_首页
P
Proofpoint News Feed
C
Check Point Blog
N
News | PayPal Newsroom
H
Heimdal Security Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
G
GRAHAM CLULEY
WordPress大学
WordPress大学
C
CERT Recently Published Vulnerability Notes
Y
Y Combinator Blog
Recorded Future
Recorded Future
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tailwind CSS Blog
W
WeLiveSecurity
L
LINUX DO - 热门话题
Microsoft Azure Blog
Microsoft Azure Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Schneier on Security
Schneier on Security
爱范儿
爱范儿
Martin Fowler
Martin Fowler
U
Unit 42
T
Troy Hunt's Blog
S
Securelist
V
V2EX
V2EX - 技术
V2EX - 技术
MongoDB | Blog
MongoDB | Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
M
MIT News - Artificial intelligence
T
Tor Project blog
Cisco Talos Blog
Cisco Talos Blog
罗磊的独立博客
小众软件
小众软件
阮一峰的网络日志
阮一峰的网络日志
Vercel News
Vercel News

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode How to add testing to an existing project Profile a React App for Performance
Tracing user interactions with React
2020-05-08 · via Kent C. Dodds Blog

This post has been archived. This API was removed in React 17.

In my post "React Production Performance Monitoring", I show you how to use React's Profiler component to monitor the performance of your application in production. The information you get from this is useful, but really all it can tell you is: "Hey, the mount/update for this tree of components took x amount of time." Then you can graph that data and identify spikes/regressions in performance for that part of your app.

It would be even useful to have information about what interactions the user performed to trigger that update. For example: "Based on the data we have, when the user clicks the dropdown toggle button, the dropdown update is fast, but when they type into the field, the dropdown update is slower."

Another benefit to interaction tracing is it adds some context to what you can visualize in the React DevTools Profiler tab. We'll get a look at that soon.

The data the Profiler calls your onRender method with has a property for interactions which is intended to provide this for you. And I want to show you how to use that API.

🚨 Please remember that this is an unstable/experimental API from React and may change when the feature is officially released.

Basic usage

React does all of its scheduling through the scheduler package. Normally you don't interact with this directly, but this package is where you're going to get the APIs to instrument your components for interaction tracing.

Let's say you have a simple greeting component:

function Greeting() {
	const [greeting, setGreeting] = React.useState('')

	function handleSubmit(event) {
		event.preventDefault()
		const name = event.target.elements.name.value
		setGreeting(`Hello ${name}`)
	}

	return (
		<div>
			<form onSubmit={handleSubmit}>
				<label htmlFor="name">Name:</label>
				<input id="name" />
			</form>
			<div>{greeting}</div>
		</div>
	)
}

When setGreeting is called, that triggers a state update. Let's assume we have reason to measure this interaction and monitor it in the long term (you don't necessarily want to add this complexity for every interaction). Here's how we'd do that:

// your other imports
import { unstable_trace as trace } from 'scheduler/tracing'

function Greeting() {
	const [greeting, setGreeting] = React.useState('')

	function handleSubmit(event) {
		event.preventDefault()
		const name = event.target.elements.name.value
		trace('form submitted', performance.now(), () => {
			setGreeting(`Hello ${name}`)
		})
	}

	return (
		<div>
			<form onSubmit={handleSubmit}>
				<label htmlFor="name">Name:</label>
				<input id="name" />
			</form>
			<div>{greeting}</div>
		</div>
	)
}

Now the interactions for this update will include information for this specific interaction based on the name of "form submitted".

The API for trace is: trace(id, startTimestamp, callbackThatTrigersUpdates)

Async tracing

So what happens if this interaction is asynchronous? Should we have one trace for the state update and then another for the update when the response comes back? Wouldn't it be better to tie these two related updates together? Yes it would! Luckily there's support for that!

Say we have to fetch the greeting from a server. Let's rewrite this for that use case:

function Greeting() {
	const [greeting, setGreeting] = React.useState('')

	// please don't judge me, I'm leaving out loading and error states and cancelation
	// to simplify this example!
	const [name, setName] = React.useState('')

	React.useEffect(() => {
		if (!name) {
			return
		}
		const onSuccess = (newGreeting) => setGreeting(newGreeting)
		fetchGreeting(name).then(onSuccess)
	}, [name])

	function handleSubmit(event) {
		event.preventDefault()
		setName(event.target.elements.name.value)
	}

	return (
		<div>
			<form onSubmit={handleSubmit}>
				<label htmlFor="name">Name:</label>
				<input id="name" />
			</form>
			<div>{greeting}</div>
		</div>
	)
}

To support tracing this, we'll use unstable_wrap:

// your other imports
import {
	unstable_trace as trace,
	unstable_wrap as wrap,
} from 'scheduler/tracing'

function Greeting() {
	const [greeting, setGreeting] = React.useState('')

	// please don't judge me, I'm leaving out loading and error states and cancelation
	// to simplify this example!
	const [name, setName] = React.useState('')

	React.useEffect(() => {
		if (!name) {
			return
		}
		trace('name updated', performance.now(), () => {
			const onSuccess = wrap((newGreeting) => setGreeting(newGreeting))
			fetchGreeting(name).then(onSuccess)
		})
	}, [name])

	function handleSubmit(event) {
		event.preventDefault()
		setName(event.target.elements.name.value)
	}

	return (
		<div>
			<form onSubmit={handleSubmit}>
				<label htmlFor="name">Name:</label>
				<input id="name" />
			</form>
			<div>{greeting}</div>
		</div>
	)
}

Cool? Yeah that's cool! And check it out, here's what that sort of thing looks like in your React DevTools:

Interactions view in DevTools

Go ahead and give it a try in your app. It definitely helps (especially the async stuff. Those little squares are clickable so you know which commits came from the interaction directly!).

You can learn more about the tracing API here.

Good luck!