DEV Community

Discussion on: How do React Fragments work under the hood?

Collapse
 
fjones profile image
FJones

It's worth noting that react now supports returning arrays from components/render (since a common use case for fragments was to wrap adjacent elements). The stark difference with explicit Fragments is that they allow adding a key prop when iterating, which lets react to optimize over it.

I would also suggest an example of how Fragment works for that purpose.

Collapse
 
fromaline profile image
Nick

Yep, you're right!
I'll consider adding this info to the article!
Thanks for the suggestion, I really appreciate it 🙏🏻

Collapse
 
loopmode profile image
Jovica Aleksic • Edited

I don't think react will optimize anything in this case, it's just that you must pass key props on array children by design, or you'll suffer at least warnings. If your array children are static and stable anyways, then you can safely ignore the warnings. Or: use a fragment instead!
The point is, arrays and fragments are not just the same thing, they have different concepts. Arrays are meant to represent dynamic children, that is: content elements that are based on dynamic data.
Fragments are meant to represent static content, that is: content that does not change dynamically, or: content that is basically hard coded.
Yes, in the end they perform similar. If you use an array without keys and ignore the warnings, then your perf will suffer and you'll have bugs when e.g users sort/drag elements. Same if you would use fragments for such dynamic content, however in that case you'd not even get any warnings.

So use fragments for static content that will not change, and enjoy the freedom of not having to specify keys.
Use arrays and provide keys for content that is rendered by iterating dynamic data.

Some comments have been hidden by the post's author - find out more