What are React keys?

August 03, 2018

React uses the key prop to keep track of items that have been changed, added, or removed from a list. Keys help your application’s performance1. Also, keys should be unique.

Let’s say we have an array of post objects. Each post has a unique slug (like how the post you’re currently reading uses the slug “react-keys” in its URL), a title, and some body information.

const posts = [
  {
    slug: 'react',
    title: 'Three reasons I like React',
    body: "Webster's Dictionary defines 'react' as..."
  },
  {
    slug: 'javascript',
    title: 'What I wish I knew about JavaScript',
    body: "Webster's Dictionary defines 'script' as..."
  },
  {
    slug: 'css',
    title: 'CSS tips for beginners',
    body: "Webster's Dictionary defines 'cascade' as..."
  },
]

const PostsList = () =>
  <div>
    {posts.map((post) => {
      <div key={post.slug}>
        <h2>{post.title}</h2>
        <div>{post.body}</div>
      </div>
    })}
  </div>
  1. To update the UI, React renders a new element tree inside the virtual DOM and compares it against the previous one. Keys help React move faster through the process of looking at lists to see if they’ve updated. ↩︎