Home > OS >  Difference between <React.Fragment> vs <>
Difference between <React.Fragment> vs <>

Time:06-03

I wanted to know the difference between <React.Fragment> versus <> in terms of the efficiency?

CodePudding user response:

I think it is mostly same, with main difference:

You can use <></> the same way you’d use any other element except that it doesn’t support keys or attributes.

More.


About efficiency, IMHO there should be no difference, at least it is not documented.

Here is brief experiment, using Test1 or Test2 inside Main gives same performance more or less, if you check using React Profiler:

let array = [...new Array(1000)];

let Test1 = (props) => {
  return (
    <>
      <div>a</div>
      <div>b</div>
      <div>b</div>
    </>
  );
};

let Test2 = (props) => {
  return (
    <React.Fragment>
      <div>a</div>
      <div>b</div>
      <div>b</div>
    </React.Fragment>
  );
};

let Main = (props) => {
  return (
    <div>
      {array.map((x) => (
        <Test2 />
      ))}
    </div>
  );
};

export default function App() {
  return (
    <div>
      <Main />
    </div>
  );
}

CodePudding user response:

It is the same thing. The <> is just a short syntax.

CodePudding user response:

Both of those will be "mapped" to exactly the same thing in the end. So IMHO there is no difference in efficiency.

CodePudding user response:

The <></> syntax is shorthand of <React.Fragmet> with a little difference. you Can't pass key or attributes to <>

someArray.map(item => (
        // Without the `key`, React will fire a key warning
        <React.Fragment key={item.id}>
          <dt>{item.term}</dt>
          <dd>{item.description}</dd>
        </React.Fragment>
      ))

The above example is not possible with <>

Check react docs for more info

  • Related