Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do not extend React.Component

the es6 syntax for creating React component is export default class ExampleComponent extends React.Component.However it still work when export default class ExampleComponent without extends React.Component on condition that import React from 'react'; why this happen

like image 881
Guichi Avatar asked Mar 29 '16 23:03

Guichi


1 Answers

It's easy to be in this situation and miss what's happening, but the difference is really huge: without extending React.Component, you're just creating a JS class. Furthermore:

  • because it satisfies the requirements of a React Class (which you can create with either React.createClass() or as an ES6 class), it'll still "work",
  • but you won't get lifeCyle methods or access to state (someone correct me if I'm wrong about this, pretty certain you wouldn't with just a class bc there's no backing instance attached).
  • these "simpler" components are generally faster for React to deal with and require less "machinery", since they're just a (hopefully) pure function that renders something.
  • so, they key difference here is that with just a class that has a render method you're not "requiring" as much. this should be enough most of the time; you shouldn't need access to state for everything

Hope that helps!

like image 131
markthethomas Avatar answered Sep 29 '22 18:09

markthethomas