Which is fastest – Pure Component, Functional Component, Class Component? [React.js] [closed]

Tags: ,



I am pretty novice in React and trying to learn up. In a recent interview the interviewer asked me the following question:

Which type of component is fastest – pure, functional or class.

I know that “functional component seems a bit faster than class-based” but thats all I know. I also don’t know why – just people say that.

Can someone let me know the order of fastness of following 4 components:

  1. Pure Functional
  2. Functional Component
  3. Pure Class-based
  4. Pure Class Component

Along, with reasoning, which one is fastest, which is slowest & why?

Thanks in advance!

Answer

I feel like this is a terrible interview question. There’s no real answer to this, it’s mostly just objective.

Here’s what Dan Abromov said in his blog back when stateful functional components started existing:

Maybe you’ve heard one of them is better for performance. Which one? Many of such benchmarks are flawed so I’d be careful drawing conclusions from them. Performance primarily depends on what the code is doing rather than whether you chose a function or a class. In our observation, the performance differences are negligible, though optimization strategies are a bit different.

Pure components can seem faster than non-pure mostly because of the optimization of not re-rendering, but if you go too far into that, you can go backwards in performance due to the many checks for equality.

That being said, the absolute fastest in react is a function. i.e. calling a function that returns jsx. Obviously you can’t use state in it. The reason this is the fastest is because it avoids a lot of the internal react code because it isn’t a separate component. Source

I.e.

function renderDivs(){
  return <div><div></div></div>
}

/// in a component:

return <div>{renderDivs()}</div>



Source: stackoverflow