The function of key in react is to determine whether the element is newly created or moved in the diff algorithm, thereby reducing unnecessary diffs, that is, to improve the efficiency of diff peer comparison and avoid in-place A side effect of reuse; key is an identifier used by react to track whether elements of the list have been modified, added or deleted.
The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.
What is the use of react's key
Function
Like Vue, React also has a diff algorithm, and the role of the element key attribute is to Determine whether the element is newly created or moved, thereby reducing unnecessary Diff
In react's diff algorithm, react will use the key of the element to determine whether the element is newly created or moved. , thereby reducing unnecessary element rendering. In addition, react also needs to determine the relationship between the element and the local state based on the key
To put it simply, it is to improve the efficiency of peer comparison of diff and avoid the side effects caused by in-situ reuse.
Vue and react themselves both use the diff algorithm. Vue uses a more fine-grained update component method, which is to bind monitors to each attribute.
react uses the automatic With the top-down update strategy, every small change will generate a new vdom for diff. If the key is not written, it will happen that it should be updated but not
What is the key?
key is an auxiliary indicator used by react to track which list elements have been modified, added or deleted. During the development process, we need to ensure that the key of an element is unique among its sibling elements.
If the list data is being rendered and a piece of data is inserted after the data, the key will not play a big role, as follows:
this.state = { numbers:[111,222,333] } insertMovie() { const newMovies = [...this.state.numbers, 444]; this.setState({ movies: newMovies }) } <ul> { this.state.movies.map((item, index) => { return <li>{item}</li> }) } </ul>
The previous elements are exactly the same in the diff algorithm. , will not generate a delete or create operation. During the last comparison, it needs to be inserted into a new DOM tree.
Therefore, in this case, it does not mean much whether the element has a key attribute
Let’s take a look at the difference between using key and not using key when inserting data earlier:
insertMovie() { const newMovies = [000 ,...this.state.numbers]; this.setState({ movies: newMovies }) }
When you have a key, react matches the sub-elements in the original tree and the latest ones based on the key attribute. For child elements in the tree, like the above situation, you only need to insert the 000 element into the front position
When there is no key, all li tags need to be modified
Similarly, it is not owned The key value represents higher performance. If only the text content has changed, the performance and efficiency will be higher if the key is not written.
The main reason is that if the key is not written, all the text content is replaced, and the nodes will not change.
Writing keys involves adding and deleting nodes. If it is found that the old key does not exist, it will be deleted. If the new key does not exist before, it will be inserted, which increases the performance overhead
Summary
Good use of key attributes is a very critical step in performance optimization. Notes are:
key should be the only one
key should not Use a random value (the random number will regenerate a number the next time it is rendered)
Avoid using index as the key
The process of react judging the key is as follows:
Recommended learning: "react video tutorial"
The above is the detailed content of What is the use of react's key?. For more information, please follow other related articles on the PHP Chinese website!

useState allows state to be added in function components because it removes obstacles between class components and function components, making the latter equally powerful. The steps to using useState include: 1) importing the useState hook, 2) initializing the state, 3) using the state and updating the function.

React's view focus manages complex application state by introducing additional tools and patterns. 1) React itself does not handle state management, and focuses on mapping states to views. 2) Complex applications need to use Redux, MobX, or ContextAPI to decouple states, making management more structured and predictable.

IntegratingReactwithotherlibrariesandframeworkscanenhanceapplicationcapabilitiesbyleveragingdifferenttools'strengths.BenefitsincludestreamlinedstatemanagementwithReduxandrobustbackendintegrationwithDjango,butchallengesinvolveincreasedcomplexity,perfo

TomakeReactapplicationsmoreaccessible,followthesesteps:1)UsesemanticHTMLelementsinJSXforbetternavigationandSEO.2)Implementfocusmanagementforkeyboardusers,especiallyinmodals.3)UtilizeReacthookslikeuseEffecttomanagedynamiccontentchangesandARIAliveregio

SEO for React applications can be solved by the following methods: 1. Implement server-side rendering (SSR), such as using Next.js; 2. Use dynamic rendering, such as pre-rendering pages through Prerender.io or Puppeteer; 3. Optimize application performance and use Lighthouse for performance auditing.

React'sstrongcommunityandecosystemoffernumerousbenefits:1)ImmediateaccesstosolutionsthroughplatformslikeStackOverflowandGitHub;2)Awealthoflibrariesandtools,suchasUIcomponentlibrarieslikeChakraUI,thatenhancedevelopmentefficiency;3)Diversestatemanageme

ReactNativeischosenformobiledevelopmentbecauseitallowsdeveloperstowritecodeonceanddeployitonmultipleplatforms,reducingdevelopmenttimeandcosts.Itoffersnear-nativeperformance,athrivingcommunity,andleveragesexistingwebdevelopmentskills.KeytomasteringRea

Correct update of useState() state in React requires understanding the details of state management. 1) Use functional updates to handle asynchronous updates. 2) Create a new state object or array to avoid directly modifying the state. 3) Use a single state object to manage complex forms. 4) Use anti-shake technology to optimize performance. These methods can help developers avoid common problems and write more robust React applications.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor
