Learn React Now
  • Table of Content
  • Design Patterns and Techniques
    • Conditional in JSX
    • Async Nature Of setState()
    • Dependency Injection
    • Context Wrapper
    • Event Handlers
    • Flux Pattern
    • One Way Data Flow
    • Presentational vs Container
    • Third Party Integration
    • Passing Function To setState()
    • Decorators
    • Feature Flags
    • Component Switch
    • Reaching Into A Component
    • List Components
    • Format Text via Component
    • Share Tracking Logic
  • Anti-patterns
    • Introduction
    • Props In Initial State
    • findDOMNode()
    • Mixins
    • setState() in componentWillMount()
    • Mutating State
    • Using Indexes as Key
    • Spreading Props on DOM elements
  • Coding Styles
  • Handling UX Variations
    • Introduction
    • Composing UX Variations
    • Toggle UI Elements
    • HOC for Feature Toggles
    • HOC props proxy
    • Wrapper Components
    • Display Order Variations
  • Performance Tips
    • Introduction
    • shouldComponentUpdate() check
    • Using Pure Components
    • Using reselect
  • Styling
    • Introduction
    • Stateless UI Components
    • Styles Module
    • Style Functions
    • npm Modules
    • Base Component
    • Layout Component
    • Typography Component
    • HOC for Styling
  • Gotchas
    • Introduction
    • Pure render checks
    • Synthetic Events
    • Related Links
Powered by GitBook
On this page
  • The bad way
  • The good way
  • Related Links:

Was this helpful?

  1. Anti-patterns

Using Indexes as Key

Keys should be stable, predictable, and unique so that React can keep track of elements.

The bad way

In this snippet each element's key will be based on ordering, rather than tied to the data that is being represented. This limits the optimizations that React can do.

{todos.map((todo, index) =>
  <Todo
    {...todo}
    key={index}
  />
)}

The good way

Assuming todo.id is unique to this list and stable, React would be able to reorder elements without needing to reevaluate them as much.

{todos.map((todo) =>
  <Todo {...todo}
    key={todo.id} />
)}

Related Links:

  • Index as a key is an anti-pattern

  • Lists and Keys

  • React docs

  • Lin Clark's code cartoon

  • ReactJS : What is the best way to give keys in array element

PreviousMutating StateNextSpreading Props on DOM elements

Last updated 4 years ago

Was this helpful?