J22Melody
J22Melody

Reputation: 205

Is it necessary for a React component to extend from React.Component?

After React 0.13 we can use ES6 Class to create React components like above:

class A extends React.Component {
  // ...
}

However if I occasionally forget to type extends React.Component, component A still works well for me as long as I don't use simple methods like this.setState().

I begin to think that is it necessary for a React component to extend from React.Component.

In architecture like FLUX or Redux there are smart React components and dumb React components.Smart ones are connected to data store while dumb ones only receive props from parents and render.I have already known in React 0.14 we can simply write a pure function for dumb ones.

However in smart components there also exists difference that some components have states while some don't.If the difference between typing extends React.Component and not is just this.setState(), I just don't extends React.Component when my component doesn't need to manage its own state.

Upvotes: 1

Views: 579

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

Is it necessary for a React component to extend from React.Component?

Not in React v0.13 but it will be in v0.14:

ES6 component classes must now extend React.Component in order to enable stateless function components. The ES3 module pattern will continue to work.

So in order to support function's as simple stateless components (what you mentioned), it seems classes need to extend React.Component.

Upvotes: 1

Related Questions