In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "how to use Transition in react18". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use Transition in react18" can help you solve the problem.
In React 18, a new concept-transition is introduced, which brings a new API--startTransition and two new hooks--useTransition and usedeferredValue.
1. Overview
This paper is divided into four parts:
The original intention of tansition
Use and introduction of startTransition
Use and introduction of useTransition
Use and introduction of useDeferredValue
2. The original intention of transition
Transtion translates directly into transition. Tansition is essentially proposed to solve the problem of rendering concurrency. Once the state of the component changes and re-rendering is triggered in React, rendering cannot be stopped. The page does not continue to respond to user interactions until the component is re-rendered.
For this reason, updates in react 18 can be divided into two categories:
Emergency update (urgent update): an update action that the user expects to respond to immediately, such as mouse clicks or keyboard input.
Transitional updates (transition update): some update operations that delay acceptable updates, such as search recommendations during queries, display of search results, etc.
/ / after being marked by startTransiton, startTransition (() = > {/ / non-emergency update) will be downgraded, and setQueryValue (inputValue)} will be delayed. / / if it is not marked, setInputValue (inputValue) will be executed immediately.
Updates marked by startTrionstion in react 18 are transitional updates (the priority of execution is lowered), and react delays the execution of internal state updates according to the internal scheduling mechanism.
Developers can use transition hook to decide which updates are marked as transition events in development. Once marked, it represents low priority execution, that is, react knows that the state can be delayed to update, by distinguishing the update priority, let the high priority events remain responsive, improve the user interaction experience, and keep the page responsive.
3. StartTransiton
Introduction to use of startTransiton
Const handleClick = () = > {/ / startTransition package marked as low priority update startTransition (() = > {setQueryValue (inputValue)}) / / execute setInputValue (inputValue)} immediately if it is not marked
First, let's introduce the simplest startTransition.
StartTransiton is a function that accepts callbacks to tell React that state that needs to be updated needs to be deferred.
If an update to a state causes the component to hang, it should be wrapped in a startTransition
Through demonstration and comparison
This is a simulation of the scene in which search results are displayed after entering characters, simulating the situation where it is easy to stutter by falsifying a large number of search results.
We try to enter 123 continuously, listen for the search box value value change (urgent update) and search value searchVal change (transition update) and output to the control bar.
Import React, {useEffect, useState, startTransition} from 'react';import'. / App.css'const SearchResult = (props) = > {const resultList = props.query? Array.from ({length: 10000}, (_, index) = > ({id: index, keyword: `${props.query}-search results ${index}`,})): [] Return resultList.map (({id, keyword}) = > ({keyword})} const App = () = > {const [type, setTpye] = useState (1) const [value, setValue] = useState (''); const [searchVal, setSearchVal] = useState ('-') UseEffect (() = > {/ / listen for search value change console.log ('response to search value update +' + searchVal +'+')} [searchVal]) useEffect (() = > {console.log ('response to input box value updates -' + value +'-') if (type = 1) {setSearchVal (value | |'-')} if (type = 2) {startTransition (() = > { SetSearchVal (value | |'-')})} [value, type]) Return (setValue (e.target.value)} / > setTpye (1)} > normal setTpye (2)} > transiton);}
In normal mode
As shown in the figure: continuous input character 123, when the first character is entered, the search value immediately responds, and the list rendering starts immediately, causing the stutter input box to stop responding to the user input, and the input box does not continue to respond until the end of the rendering.
After using startTransition
As shown in the figure: continuous input character 123, the input box continues to respond, the response of the search value is delayed to ensure page feedback, until the end of the input, it begins to respond to the search value, render the search results, and maintain the response of the page.
4. UseTransiton
Introduction to use of useTransiton
Import {useTransiton} from 'react'const [isPending, startTransition] = useTransiton ({timeoutMs: 2000}) / / for example, in the pending state, you can display a Spinner {isPending?
< Spinner />: null}
StartTransition is a function that accepts callbacks to tell React that state that needs to be updated needs to be deferred.
IsPending is a Boolean value, which is how react tells us whether to wait for the transition to complete.
UseTransition accepts the value of a delayed response with timeoutMs, and if it is not completed within a given timeoutMs, it will force an update of the state in the startTransition callback function.
UseTransiton simple analysis
Let's understand useTransition through pseudo-code.
Function useTransition () {const [isPending, setPending] = mountState (false); const start = (callback) = > {setPending (true); / / through transiton mode, low-priority scheduling executes callback functions / / to reduce the priority of updates. If the priority of the update triggered in the callback is low, / / it will give way to a high-priority update, or if the current transaction is busy, it will be scheduled to be applied in the next idle period. Scheduler.unstable_next (() = > {const prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = 1; try {setPending (false); / / implement the callback function callback ();} finally {ReactCurrentBatchConfig.transition = prevTransition;}})} return [isPending, start] }
During the execution of startTransition, the setPending is triggered twice, once before the transition=1 and once after. SetPending (true) when startTransition is called, and transiton transition task updates setPending (false) when the callback function within startTransition executes. React can accurately grasp the waiting transition time according to the change of setting value, and determine whether the update is enforced beyond the timeoutMs (if any).
5. UseDeferredValue
Introduction to use of useDeferredValue
Const [value, setValue] = useState ('') / / defferedValue value is deferred to state update const deferredValue = useDeferredValue (value, {timeoutMs: 2000})
UseDeferredValue returns the status of a delayed response, and the maximum delay time timeoutMs can be set.
You can pass in an optional timeoutMs, which will force updates if it is not completed within a given timeoutMs.
Unlike useTransition, useTransition deals with a piece of logic, while useDeferred generates a new state.
The use of useDeferredValue
Import React, {useEffect, useState, useTransition, useDeferredValue} from 'react';import'. / App.css'const SearchResult = (props) = > {const resultList = props.query? Array.from ({length: 10000}, (_, index) = > ({id: index, keyword: `${props.query}-search results ${index}`,}): []; return resultList.map (({id, keyword}) = > ({keyword})} const App = () = > {const [value, setValue] = useState ('') Const searchValue = useDeferredValue (value, {timeoutMs: 2000}) UseEffect (() = > {console.log ('response to input box values -' + value +')}, [value]) useEffect () = > {/ / listen for search values to change console.log ('update responses to search values +' + searchValue +'+')} [searchValue]) return (setValue (e.target.value)} / > useDeferredValue) }
UseDeferredValue simple analysis
Let's understand useDeferredValue through pseudo-code.
Function useDeferredValue (value) {const [prevValue, setValue] = updateState (value); updateEffect (() = > {/ / update value through transition mode in useEffect. Scheduler.unstable_next (() = > {const prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = 1; try {setValue (value);} finally {ReactCurrentBatchConfig.transition = prevTransition;})}, [value]); return prevValue;}
UseDeferredValue listens for changes in incoming values through useEffect, and then performs changes in values through the transition task. This ensures that the update of defrredValue lags behind setState and conforms to the principle of transitional update because it is performed through the transition scheduling mechanism.
This is the end of the content about "how to use Transition in react18". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.