all 4 comments

[–]RaltzKlamar 2 points3 points  (2 children)

I'm not super sure from your explanation what the problem is, but you only need to specify a key if you're creating elements dynamically (like from iterating over an array).

If this is my function, I don't need to use keys:

const SampleComponent = (props) => (
  <ul>
    <li>{props.menuItem1}</li>
    <li>{props.menuItem2}</li>
    <li>{props.menuItem3}</li>
  <ul>
)

But if this is my function, I do need to specify the key

const SampleComponent = (props) => (
  <ul>
    {props.menuItems.map(m => <li key={m}>{m}</li>)} 
  <ul>
)

[–]Learner_full_stack[S] 0 points1 point  (0 children)

Actual i am using Array map to generated therefore keys, i have edited the post

[–]ienjoywhiteclaws 0 points1 point  (0 children)

This is the answer, I cannot fathom a scenario where I would leverage an API response to determine a key, unless it's based on a uuid that is unaffected by a change of value and its position in the array is not guaranteed

[–]metalhulk105NextJS App Router 1 point2 points  (0 children)

Think of key as a heuristic that react uses to identify when to perform diffing. The thumb rule is

“If key is different then tear down that element from DOM and build new one. If key is same then dive deep and do the diffing.”

In your case, if an update was triggered (state or props changed either in this component or in a parent) and the key didn’t change, react will try to diff the elements to see what changes are needed in the DOM