Bad ways you’re using react – React Fragments

Share This Post

Welcome back to our ongoing series on common React pitfalls! In this 10th installment, we’ll be diving into the world of React Fragments and why they shouldn’t be ignored. If you haven’t had a chance to check out the previous parts of this series, I highly recommend giving them a read, as they cover essential React best practices and anti-patterns.

In this article, we’ll explore the importance of React Fragments, how to use them effectively, and the potential downsides of ignoring them. By the end of this post, you’ll have a better understanding of why React Fragments deserve a place in your React toolbox and how they can help you write cleaner, more efficient code. So let’s dive in and discover the magic of React Fragments!

What are reacted fragments?

React Fragments are an incredibly useful, yet often overlooked, feature introduced in React 16.2. They provide a clean and efficient way to return multiple elements from a component without the need for extra, unnecessary DOM elements. This seemingly small improvement can lead to more readable code and improved performance in your application. Unfortunately, many developers still neglect this powerful feature, leading to cluttered and less performant code.

Why should you use react fragments?

Cleaner, more readable code: React Fragments offer the advantage of simplifying code and boosting readability. Without fragments, developers often wrap multiple elements in a parent container to meet React’s single root element requirement, leading to cluttered DOM structures. By using React Fragments, you can return multiple elements without extra DOM nodes, resulting in cleaner, more concise, and easily understandable code.

Improved performance: Unnecessary DOM elements impact both code readability and performance. Excess elements can slow down rendering, increase memory usage, and degrade the user experience. Utilizing React Fragments to remove superfluous wrapper elements reduces the number of DOM nodes, resulting in improved performance, particularly in larger applications with intricate component hierarchies.

Better CSS styling and layout: Extra wrapper elements can sometimes disrupt CSS styling and layout, causing unexpected behavior or conflicts with existing styles, and necessitating workarounds and adjustments. React Fragments enable a cleaner, flatter DOM structure, making it simpler to apply CSS styles and manage your application’s layout, reducing the likelihood of encountering styling or layout issues.

Enhanced accessibility: Unnecessary wrapper elements can negatively affect your application’s accessibility, as extra elements may interfere with screen readers or assistive technologies, hindering interaction for users with disabilities. React Fragments enhance accessibility by reducing DOM complexity, enabling assistive technologies to navigate your application more efficiently. Using fragments contributes to a more accessible web experience for all users.

An example

Let’s consider a more complex example that demonstrates the four benefits of using React Fragments — cleaner code, improved performance, better CSS styling, and enhanced accessibility.

Suppose you have a component that renders a user profile, including their name, job title, avatar, and a list of skills. Without using React Fragments, your component might look like this:

import React from 'react';

function UserProfile({ firstName, lastName, jobTitle, avatarURL, skills }) {
  return (
    <div>
      <div>
        <h1>{firstName} {lastName}</h1>
        <h2>{jobTitle}</h2>
      </div>
      <div>
        <img src={avatarURL} alt={`${firstName} ${lastName}'s avatar`} />
      </div>
      <div>
        <h3>Skills:</h3>
        <ul>
          {skills.map((skill, index) => (
            <div key={index}>
              <li>{skill}</li>
            </div>
          ))}
        </ul>
      </div>
    </div>
  );
}

export default UserProfile;

Notice how we’re using multiple div elements to wrap different parts of the user profile, which can lead to the issues we discussed earlier.

Now, let’s rewrite this component using React Fragments:

import React from 'react';

function UserProfile({ firstName, lastName, jobTitle, avatarURL, skills }) {
  return (
    <>
      <header>
        <h1>{firstName} {lastName}</h1>
        <h2>{jobTitle}</h2>
      </header>
      <figure>
        <img src={avatarURL} alt={`${firstName} ${lastName}'s avatar`} />
      </figure>
      <section>
        <h3>Skills:</h3>
        <ul>
          {skills.map((skill, index) => (
            <React.Fragment key={index}>
              <li>{skill}</li>
            </React.Fragment>
          ))}
        </ul>
      </section>
    </>
  );
}

export default UserProfile;

In this revised version, we’ve replaced the unnecessary div elements with more semantic HTML elements (like header, figure, and section) and used React Fragments (in both short and long syntax) to avoid extra wrapper elements.

The benefits of this refactored version are:

  1. Cleaner code: The component is now more readable, as the structure is flatter and semantic elements provide context to the content.
  2. Improved performance: We’ve reduced the number of DOM nodes, which can positively affect rendering performance in more complex applications.
  3. Better CSS styling: Using semantic elements and a flatter structure reduces the chance of layout or styling issues caused by excessive nesting.
  4. Enhanced accessibility: Semantic elements and a simpler DOM structure make it easier for assistive technologies to interpret and navigate the content.

By using React Fragments, we’ve improved the overall quality of our UserProfile component in multiple ways, demonstrating the power and versatility of this feature.

Leave a Reply

Digital art dealers

Join our vibrant community of more than 750 members by subscribing to our newsletter. Every Monday, you'll receive a programming meme to kickstart your week.

follow us on

© 2023 Digital Art Dealers. All rights reserved.

%d bloggers like this: