Fragments and keys are essential React features for clean component structure and efficient rendering. Here's how to use them.
React Fragments
Why Not Div Wrappers?
Fragments with Keys
Understanding Keys
Good vs Bad Keys
When Index Keys Are Okay
Key Behavior Demonstration
Resetting Components with Keys
Generating Keys
Fragments in Conditional Rendering
Nested Fragments
Common Patterns
Best Practices
Fragments:
✓ Use <> for simple grouping
✓ Use <Fragment> when keys needed
✓ Avoid unnecessary wrapper divs
✓ Keep DOM structure clean
Keys:
✓ Use unique, stable IDs
✓ Use database IDs when available
✓ Generate IDs at creation time
✓ Use key to force remount
Avoid:
✗ Index as key for dynamic lists
✗ Random keys on each render
✗ Non-unique keys among siblings
✗ Unnecessary Fragment nesting
Performance:
✓ Keys enable efficient diffing
✓ Stable keys prevent remounting
✓ Fragments reduce DOM nodes
✓ Proper keys preserve state
Conclusion
Fragments let you group elements without adding extra DOM nodes - use the short syntax <> when possible, and <Fragment> when you need keys. Keys help React efficiently update lists - always use unique, stable identifiers. Avoid index keys for dynamic lists, and remember that changing a key forces a component to remount, which can be useful for resetting state.