DEV Community

Cover image for Are you giving the proper sense to React.Fragment?

Are you giving the proper sense to React.Fragment?

Coding Bugs on April 24, 2021

UPDATE: Title has been changed because of the misunderstanding around it and the content. I hope this change will cover the expectations and keep ...
Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

The title is clickbait and React.Fragment (<></>) has very valid use cases. The example you showed technically doesn't need to return a fragment—you can just do return !isEmpty && (...). Or just return null if it's empty, depending on what your preference is.

There are other valid use cases for fragments, too, like if you need to return two siblings but without introducing unnecessary wrapper parents.

Collapse
 
codbugs profile image
Coding Bugs

My apologies if you feel the title is clickbait. That wasn't my intention at all.

My article wants to point out that we should use the tools provided by frameworks and libraries in the scope of our domain solution. Returning React.Fragment as an empty list is something valid and will work but it doesn't mean nothing if we, as programmers, don't give it a meaning. Everything depends on requirements and, maybe, we don't need to deep dive in a big file structure with lots of components because it increase complexity.

Collapse
 
anicholson profile image
Andy Nicholson • Edited

Your final code reads very well, that’s to be commended.

I don’t agree that the solution to every React problem is more components, though. Writing a ListManager component seems like massive overkill and poor naming: what you're describing is more like a ListItemManager - and what is a ListItemManager if not, well, a List?

Naming an empty list is great, but you don’t need a component for that either! You could do just as well by interpolating a const instead, saving yourself a function call:

function List(props) {  
  const items = props.items;
  const emptyList = <React.Fragment />;
  const hasItems = items && items.length > 0;

  return hasItems
  ?  <ul>{ items.map(i => <li key={i}>{i}</li>) }</ul>
  : emptyList
  ;
}
Enter fullscreen mode Exit fullscreen mode

React is awesome, but moar components aren’t always the answer.

Collapse
 
jackritenour profile image
jackritenour

Very good points.

Collapse
 
imervinc profile image
👺Mervyn • Edited

IMO:
If your gonna return an empty fragment you might as well return null.
And if your goal is readability, you can always use multiple return like this

function List(props) {  
  const items = props.items;

  // check if items is not empty
  const isEmpty = !(items && items.length > 0);

   if(isEmpty) return null

  return(
      <ul>
        { items.map(i => <li key={i}>{i}</li>) }
      </ul>
      );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
andrewbridge profile image
Andrew Bridge

This is exactly what I came to the comments hoping to post, thanks for getting there first!

I'm baffled to see such a simple example turned into such a lot of code and it exemplifies the over-engineering the React community appears to deal with. Replace null with <React.Fragment /> if you must but creating a list shouldn't take 10s of lines of code.

Collapse
 
kmturley profile image
Kim T

Multiple returns which both return the same type (html) is the most readable and reusable

Collapse
 
sergeysova profile image
Sergey Sova

I prefer this over returning fragment.
But in the most situations we need an empty state component instead of null

Collapse
 
mattcoady profile image
Matt Coady

Null is more performant too. With null there's nothing for react to process, it just moves on. A fragment has to be processed, even if it isn't very much.

Collapse
 
cullophid profile image
Andreas Møller • Edited

I much prefer this version:

return items && 
        <ul>
        { items.map(i => <li key={i}>{i}</li>) }
      </ul>;
Enter fullscreen mode Exit fullscreen mode
  • The logic is inlined so you don't have to jump between component when reading the code.

  • You won't have ever new dev on your team asking you why you are returning and empty fragment.

The final example looks more "clean", but what actually happens is that you have to jump around in the file a lot to understand what is happening.

Collapse
 
codbugs profile image
Coding Bugs

Agree with your last point. We should balance the benefits of creating components and get a complex solution from a file structure point of view.

Collapse
 
cullophid profile image
Andreas Møller

And we need to stop promoting ideas like DRY and Single Responsibility Principle, which are at best pointless and at worst harmful.

Collapse
 
pracoon profile image
Prasham Ashesh

I wish one day I'd be able to express my, points in such linear and organized way!
Good read! definitely scales me up!

Collapse
 
codbugs profile image
Coding Bugs

Thanks @pracoon

Collapse
 
pcjmfranken profile image
Peter Franken

Fragments were introduced as a workaround to JSX not supporting unwrapped sibling elements.

Professional programmers should probably start by reading the docs.

Collapse
 
dmauldin profile image
Dave Mauldin

Full agree. Also, if the docs were read in this case, one would also see that the official advice is to return false ala return condition && <li>item</li> so that React immediately knows to not render anything. Not sure where the expectation that the component must return something renderable came from in this article.

Collapse
 
willsmart profile image
willsmart

I'm confused 🤔
Do you mean to say you're a coder but don't do it professionally?
Like, if you were a professional programmer you wouldn't have returned a fragment (since they don't do that sort of thing) but would have just returned null and been done with it?

Anyway, I totally agree that to be effective as a coder you need to have all the tools in the toolkit at your disposal, and know the situations where they're useful.

To me, fragments' domain of usefulness is for encapsulating multiple elements, or unknown numbers of elements, as one return value. If I'm returning zero elements, I'll return null since that is what null means: a typed but missing value.

Collapse
 
anxiny profile image
Anxiny

Fragment is very useful when you need to have a parent that does not need to render a container but need to render its children.
From example the Context Provider, component from react-router-dom.

Collapse
 
leischj profile image
leischj • Edited

I'm so confused. The title of the article says professionals never return "React.Fragment" but by the end of the article you have a component (EmptyList) that returns "React.Fragment" Does this mean you're not a professional?

In your first edit you have a comment to point out the added complexity, but the final edit has a ton of needless complexity, but is missing that comment.

Returning null for an empty list is perfectly testable, acceptable, and most importantly, simple. All things being equal, I'll opt for simplicity.

Collapse
 
codbugs profile image
Coding Bugs

Totally agree with the requirements specification and domain model comments. My intention in this article is to show an example of how framework features have to be adapted to our solution and not in the opposite.

Collapse
 
doabledanny profile image
Danny Adams

Makes a lot of sense, thanks for writing and sharing this!

Collapse
 
codbugs profile image
Coding Bugs

Nice comment @doabledanny

Collapse
 
geewhizbang profile image
Geoffrey Swenson

Is this just an example of how irritating React is that you have to worry about all sorts of arcane stuff like this?

I'm using Vue 3 right now really liking the way it handles things more elegantly.