React Fragments and Strict Mode

In this tutorial, we will explore two essential React features: Fragments and Strict Mode. Fragments allow you to group multiple elements without adding unnecessary nodes to the DOM, while Strict Mode is a development tool that helps highlight potential problems in an application.

1. React Fragments

A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

JavaScript

import React, { Fragment } from 'react';

function List() {
  return (
    <Fragment>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </Fragment>
  );
}

// Short syntax (Empty Tags)
function ShortList() {
  return (
    <>
      <li>Item A</li>
      <li>Item B</li>
    </>
  );
}          

Note: The short syntax <></> does not support keys. If you need to pass a key to a Fragment (e.g., inside a loop), you must use the explicit <Fragment> syntax.

2. Strict Mode

StrictMode is a tool for highlighting potential problems in an application. Like Fragment, StrictMode does not render any visible UI. It activates additional checks and warnings for its descendants.

JavaScript

import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

const root = createRoot(document.getElementById('root'));
root.render(
  <StrictMode>
    <App />
  </StrictMode>
);          

Why use Strict Mode?