Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 997
iuliu.net Avatar asked Sep 29 '17 07:09

iuliu.net


People also ask

Why we need to extend React component?

Using the extends keyword, you can allow the current component to access all the component's properties, including the function, and trigger it from the child component. This example creates one component called ParentClass.

Do I need to extend component in React?

If you want to write a component that takes advantage of the lifecycle methods you will need to extend the default Component class. The Component class contains the lifecycle methods and should not be confused with other generic react components, such as functional components or any component you may write.

Why we use component in React Native?

Native Components​ At runtime, React Native creates the corresponding Android and iOS views for those components. Because React Native components are backed by the same views as Android and iOS, React Native apps look, feel, and perform like any other apps. We call these platform-backed components Native Components.

Why do we need component did mount?

The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered.


1 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.

like image 74
Huy Vo Avatar answered Oct 14 '22 02:10

Huy Vo