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

推荐订阅源

Google DeepMind News
Google DeepMind News
C
CERT Recently Published Vulnerability Notes
C
Cisco Blogs
Cloudbric
Cloudbric
The Last Watchdog
The Last Watchdog
L
LINUX DO - 热门话题
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Security Archives - TechRepublic
Security Archives - TechRepublic
TaoSecurity Blog
TaoSecurity Blog
V2EX - 技术
V2EX - 技术
H
Heimdal Security Blog
S
Security Affairs
L
Lohrmann on Cybersecurity
Hacker News - Newest:
Hacker News - Newest: "LLM"
Simon Willison's Weblog
Simon Willison's Weblog
WordPress大学
WordPress大学
小众软件
小众软件
Security Latest
Security Latest
AWS News Blog
AWS News Blog
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
Engineering at Meta
Engineering at Meta
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
F
Full Disclosure
S
Schneier on Security
L
LangChain Blog
MyScale Blog
MyScale Blog
Know Your Adversary
Know Your Adversary
P
Privacy International News Feed
Google Online Security Blog
Google Online Security Blog
Scott Helme
Scott Helme
Stack Overflow Blog
Stack Overflow Blog
爱范儿
爱范儿
A
Arctic Wolf
Martin Fowler
Martin Fowler
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
The Register - Security
The Register - Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园_首页
Latest news
Latest news
F
Fortinet All Blogs
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
Hacker News: Ask HN
Hacker News: Ask HN

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Don't Stop Me Now: How to Use React useTransition() hook
Dmitri Pavlutin · 2021-06-23 · via Dmitri Pavlutin Blog

Some UI updates should be performed as quickly as possible (typing into an input field, select a value from dropdown), while others can have lower priority (filtering a list).

Until now, React hasn't provided a tool to prioritize UI updates.

Fortunately, starting React 18 (which is in alpha as of June 2021) you can enable the concurrent mode — which allows you to mark UI updates as high or interruptible-low priority.

In this post, you'll learn how to use useTransition() hook to mark UI updates as low priority, which is especially useful for heavy non-urgent updates.

1. useTransition() hook

By default, all updates in React are considered urgent. That could create a problem when quick updates are slowed down by heavy updates.

React Legacy Rendering Mode

However, starting React 18 and the new concurrency features, you can mark some updates as interruptible and non-urgent — so-called transitions. That's especially useful with heavy UI updates, like filtering a big list.

React Concurrent Rendering Mode

useTransition() is the hook that lets you access concurrent mode features inside of the React component.

Invoking const [isPending, startTransition] = useTransitionHook() returns an array of 2 items:

  • isPending: indicates that the transition is pending
  • startTransition(callback): allows you to mark any UI updates inside callback as transitions.


import { useTransition } from 'react';

function MyComponent() {

const [isPending, startTransition] = useTransition();

// ...

const someEventHandler = (event) => {

startTransition(() => {

// updates as transitions

setValue(event.target.value);

});

}

return <HeavyComponent value={value} />;

}


In order to use useTransition() hook, make sure to enable the concurrent mode.

2. Heavy UI updates as urgent

Let's consider an example when all updates are urgent, and how does it affect the user experience.

You have a list of employee names, as well as an input field where the user introduces a query. The component highlights the query matches in the employee names.

Here's a possible implementation:


import { useState } from 'react';

export function FilterList({ names }) {

const [query, setQuery] = useState('');

const changeHandler = ({ target: { value } }) => setQuery(value);

return (

<div>

<input onChange={changeHandler} value={query} type="text" />

{names.map((name, i) => (

<ListItem key={i} name={name} highlight={query} />

))}

</div>

);

}

function ListItem({ name, highlight }) {

const index = name.toLowerCase().indexOf(highlight.toLowerCase());

if (index === -1) {

return <div>{name}</div>;

}

return (

<div>

{name.slice(0, index)}

<span className="highlight">

{name.slice(index, index + highlight.length)}

</span>

{name.slice(index + highlight.length)}

</div>

);

}


Open the demo.

<FilterList names={names} /> accepts a big array of names. Inside of the component, query is the state variable that contains the query string. The input field is a controlled component that updates query state variable when the user types.

Open the demo and quickly type a query into the input field. You would notice typing lags and the UI feels unresponsive for noticeable periods.

Why does it happen, and how to solve it?

Updating the input field value when the user types is an urgent task that must perform fast. However, updating the list by highlighting the matches is a heavy but non-urgent task.

The heavy non-urgent task slows down the light urgent task.

useTransition() hook can help you separate urgent from non-urgent UI updates.

3. Heavy UI updates as transitions

As already mentioned, you can use useTransition() hook to let know React which UI updates are urgent (like updating the input field value), and which are non-urgent transitions (like updating the names list to highlight the query).

Let's make the necessary adjustments to <FilterList> component.

First, let's invoke the [isPending, startTransition] = useTransition() hook to get access to startTransition() function. Secondly, let's create a state variable to hold the query state value specifically for the transition.


import { useState, useTransition } from 'react';

export function FilterList({ names }) {

const [query, setQuery] = useState('');

const [highlight, setHighlight] = useState('');

const [isPending, startTransition] = useTransition();

const changeHandler = ({ target: { value } }) => {

setQuery(value);

startTransition(() => setHighlight(value));

};

return (

<div>

<input onChange={changeHandler} value={query} type="text" />

{names.map((name, i) => (

<ListItem key={i} name={name} highlight={highlight} />

))}

</div>

);

}


Open the demo.

Open the demo using transitions feature. If you type quickly a query into the input field, you would notice a delay in highlighting the query inside the list.

React has separated the rendering of the urgent task (updating the input field when the user types) from the non-urgent task (highlighting the query inside the list). Such an approach provides a better user experience.

4. Conclusion

The concurrent mode in React lets you separate urgent from non-urgent tasks, making the UI updates more user-friendly.

After enabling the new React 18 concurrent mode, you can use the useTransition() hook to access startTransition(callback) function.

startTransition(callback) let's you mark certain updates as transitions:


const [isPending, startTransition] = useTransition();

startTransition(() => {

// updates as transitions

setStateValue(newValue);

});


Side challenge: is it possible to use useDeferredValue() hook to get rid of the duplicate state highlight in <FilterList>? If so, write your solution in a comment below!