Why should you `extend` Component in React (Native)?

Viewed 9681

I'm quite new in this react ecosystem, but it's pretty clear so far on what a component is and how to create one using:

export default class NotificationsScreen extends Component {
    render() {
        return(<View></View>);
    }
}

however I've seen some examples that just use

const MySmallComponent = (props) => <View></View>

And the app seems to work just as fine..

What is the advantage of extending Component?

2 Answers

Since React is strongly connected to functional programming, it's always a good habit to write pure functions in React. If your component doesn't need to manage state or involve lifecycle methods then use stateless component:

  1. It just feels more natural that way
  2. Easier to write, easier to read
  3. No extends, state and lifecycle methods mean faster code

You can even find more reasons at this article. So, all I want to say is, always use stateless component if you don't need to manage its state.

Dan Abramov coined the terms Smart and Dumb components. Later, he called them Container and Presentational components. So

export default class NotificationsScreen extends Component {
    render() {
        return(<View></View>);
    }
}

is a Container and

const MySmallComponent = (props) => <View></View>

is Presentational components.

Presentational Components are only used for presentaion purposes i.e they rarely have their own state and they are just used to show data on UI by receiving props from parent component or include many child component inside of them. Presentational Component don't make use of react lifecycle methods.

Where as Smart components or Containers usually have state of their own and make use of lifecycle methods of react and also these components usually have their own state.

Related