DocumentationRulesno-useless-fragment

no-useless-fragment

Rule category

Correctness.

What it does

Prevents the use of useless fragments.

Why is this bad?

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.

Moreoever, rendering fragments with multiple levels of depth can cause React to not retain the state of components nested within the fragment after certain re-renders, which may lead to unexpected state resetting.

Examples

Failing

<><Foo /></>
 
<p><>foo</></p>
 
<></>
 
<section>
  <>
    <div />
    <div />
  </>
</section>

Passing

{foo}
 
<Foo />
 
<>
  <Foo />
  <Bar />
</>
 
<>foo {bar}</>
 
<> {foo}</>
 
<>{children}</>
 
<>{props.children}</>
 
const cat = <>meow</>
 
<SomeComponent>
  <>
    <div />
    <div />
  </>
</SomeComponent>
 
<Fragment key={item.id}>{item.value}</Fragment>

Note

By default, this rule always allows single expressions in a fragment. This is useful in places like Typescript where string does not satisfy the expected return type of JSX.Element. A common workaround is to wrap the variable holding a string in a fragment and expression. To change this behaviour, use the allowExpressions option.

Examples of correct code for single expressions in fragments:

<>{foo}</>
 
<Fragment>{foo}</Fragment>

Examples with allowExpressions: false

Failing

<><Foo /></>
 
<p><>foo</></p>
 
<></>
 
<Foo bar={<>baz</>} />
 
<section>
  <>
    <div />
    <div />
  </>
</section>
 
const cat = <>meow</>
 
<>{children}</>
 
<>{props.children}</>
 
<> {foo}</>
 
<SomeComponent>
  <>
    <div />
    <div />
  </>
</SomeComponent>

Passing

{foo}
 
<Foo />
 
<>
  <Foo />
  <Bar />
</>
 
<>foo {bar}</>
 
<Fragment key={item.id}>{item.value}</Fragment>

Further Reading