Back to Blog
ReactFragmentsKeysPerformance

React Fragments and Keys Guide

Master React Fragments for cleaner JSX and keys for efficient list rendering.

B
Bootspring Team
Engineering
October 27, 2018
6 min read

Fragments and keys are essential React features for clean component structure and efficient rendering. Here's how to use them.

React Fragments

Loading code block...

Why Not Div Wrappers?

Loading code block...

Fragments with Keys

Loading code block...

Understanding Keys

Loading code block...

Good vs Bad Keys

Loading code block...

When Index Keys Are Okay

Loading code block...

Key Behavior Demonstration

Loading code block...

Resetting Components with Keys

Loading code block...

Generating Keys

Loading code block...

Fragments in Conditional Rendering

Loading code block...

Nested Fragments

Loading code block...

Common Patterns

Loading code block...

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.

Share this article

Help spread the word about Bootspring

Related articles