← react hacks / react / using-fragment-for-cleaner-jsx.md

Using Fragment for Cleaner JSX in React

Learn how to use React.Fragment for cleaner JSX and improved performance. This hack guide simplifies the use of fragments in your React code.

React Fragments allow you to return multiple elements from a component’s render method without creating an additional DOM element. They help in wrapping up multiple elements, leading to a cleaner and more readable JSX.

Here is an example of its usage:

import React, { Fragment } from 'react';

function Component() {
  return (
    <Fragment>
      <h1>Title</h1>
      <p>Description</p>
    </Fragment>
  );
}

As you can see, instead of a div or any other wrapper, we are using Fragment which doesn’t add any extra nodes to the DOM. This results in a more optimized and efficient code.

You can also use the short syntax for Fragments:

function Component() {
  return (
    <>
      <h1>Title</h1>
      <p>Description</p>
    </>
  );
}

This reduces clutter in your JSX and aids in making your code cleaner and easier to understand. Happy coding!

Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. 3450e43 Enhancing Your Coding Experience with Neovim: A Beginner’s Guide

    tag: neovimtag: codingtag: productivity

  2. 9676c32 Understanding Neovim: How to Customize and Improve Your Text Editor

    tag: neovimtag: text-editortag: customization

  3. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  4. 2c098c3 Avoiding Unnecessary Re-renders with React.memo

    tag: reacttag: web developmenttag: performance optimization

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?