Contents of React Interview Questions

Comprehensive collection of React interview questions and answers covering hooks, components, state management, and best practices.

Fragments vs Container Divs in React

In React, Fragments and container <div>s are two ways to group multiple elements. However, they serve different purposes and have different impacts on the rendered DOM.

1. Container <div>s

Traditionally, to return multiple elements from a component, developers wrapped them inside a <div>. Example:

function App() { return ( <div> <h1>Hello</h1> <p>Welcome to the app.</p> </div> ); }

Issues with using extra <div>s:

  • Unnecessary DOM nodes: Adds extra <div>s that are not semantically meaningful.
  • CSS complications: Extra nodes can make styling harder and more brittle.
  • Accessibility concerns: Extra divs may confuse screen readers or keyboard navigation if not handled properly.

2. React Fragments

Fragments allow you to group multiple elements without adding extra nodes to the DOM.

Example using a Fragment:

import { Fragment } from 'react'; function App() { return ( <Fragment> <h1>Hello</h1> <p>Welcome to the app.</p> </Fragment> ); }

Or using the shorthand syntax:

function App() { return ( <> <h1>Hello</h1> <p>Welcome to the app.</p> </> ); }

Advantages of Fragments:

  • No extra DOM nodes: Keeps the HTML clean and lightweight.
  • Better performance: Avoids unnecessary wrappers.
  • Easier styling and layout: You don't have to manage extra divs in your CSS.
  • Improved accessibility: No irrelevant nodes for screen readers.

When to Use What?

ScenarioUse a FragmentUse a Container <div>
Need to group elements without affecting DOM structure
Need a wrapper for CSS styling, layout, or semantics

Tip: Always prefer Fragments unless you specifically need a real DOM element (like for styling with Flexbox/Grid, or adding classes/IDs).


Quick Example: Why Fragments Are Better

Without Fragment:

<div> <h1>Hello</h1> <p>Welcome</p> </div>

With Fragment:

<h1>Hello</h1> <p>Welcome</p>

👉 Cleaner HTML, better performance!