javascriptreactjstypescript

Is there way to use Symbol in React JS like base for key in map function


By the React docs is specified that key value in React lists should be unique. So, in that way, best choice is use ids from our database on client side like a key when we use map for our lists.

But if have some data that would be generated on our client side we can use UUID (thit is from React doc), but can we use Symbol instead?

Maybe are there any other good reasons to use Symbol in React (just like second additional question; u can answer it in short)?


Solution

  • The short answer is no: the key prop if present should be string | null. Those Typescript types are maintained AFAIK by the React team at Facebook so they should be presumed to be authoritative.

    The longer answer is that typically you are assigning a key prop inline on every render and the diffing algorithm checks if it's changed since the last one, something like this:

    function MyComponent({ items }) {
      return items.map(item => <div key={Symbol()}>{item.description}</div>);
    }
    

    That will create a new unique Symbol on every render (and according to Estus Flask in the comments, error at runtime!), which is not what you want. There are many legitimate uses of Symbol in Javascript, but this isn't one of them: the point of the key prop is to give list elements a stable identity across renders.