11/19/2023 0 Comments For each reactjsNow you know how to render lists in React. Songs (Spotify), thoughts (Twitter), activities (Toggl). It’s been said that most web apps are just lists of things. So the general rule is, if your list items have a unique id property of some sort, use that as your key. Think about what happens in those situations: a new item replaces the one at index “0”, but to React, that item is unchanged because it’s still called “0”, so it doesn’t re-render. fetching a new list from the server), things may not render as expected. If the list can be sorted, or you might replace items with new items (e.g. If on the other hand, the items could be reordered at some point, that will cause weird rendering bugs. If you know for sure that the list of items is static, then the array index is a fine choice. So, Math.random is a bad choice for a key (it’ll change every time… and it might not be unique (slim chance of that, though))īack to the problem at hand: why isn’t an item’s array index always a good choice for a key? It seems to be unique and permanent… Permanent – An item’s key must not change between re-renders, unless that item is different.So, person.firstName would be a bad choice, for example (might not be unique). Unique – Every item in the list must have a unique key.React can look at the key and know that, yes, even though this is not strictly = to the old, it actually is the same because the keys are the same. The next time that component renders, React will say, “I already have some list items on screen – are these ones different?” It will avoid recreating DOM nodes if it can tell that the items are the same.īut here’s the important bit: React can’t tell with a simple equality check, because every time a JSX element is created, that’s a brand new object, unequal to the old one. The first time a component like IdiomaticReactList is rendered, React will see that you want to render a bunch of items, and it will create DOM nodes for them. Remember React uses a virtual DOM, and it only redraws the components that changed since the last render. React relies on the key to identify items in the list. (The best choice for a key is an item’s unique ID, if it has one.) This is actually not a great idea in all cases, and I’ll tell you why. You might’ve noticed I used the item’s array index as the key prop in both examples above. Function IdiomaticReactList ( props ) A Note on the key Prop
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |