There are some differences between method component and class component. I'll try to highlight some of it, and when to use it.
Method Component
The simplest way to declare a component in React. We only need to declare a method that returns a jsx syntax and it's done. Below is an example:
We can also pass something into the component using props. This props will be the first parameter on the method component.
Class Component
This is the robust version of the component. With class component you can do more. Props will by default, included in the class (this.props). You can use state, kinda local variable for your component. You may intruduce many class' method that share the same state. And don't forget to be careful with object binding, I often use the arrow method to avoid object binding problem.
Class component also allows you to use lifecycle method. It's kinda bunch of methods that will be called in particular event like component mount, updated, unmount, etc.
You can see the diagram of lifecycle here:
http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
When to Use Class Component or Method Component
The major reason to not using class component is when you only need a simple component or dumb component like a button, card, or representational component. If your component doesn't need a complex state, not using lifecycle, method component is best for you. And vice versa.
Sometimes, I'm not sure if my component will suits method or class component. In this case, I prefer to use class component from the beginning, so I don't need to change anything if I need more robust component.
Bonus
If you are using VS Code, you can install a React plugin:
https://marketplace.visualstudio.com/items?itemName=dsznajder.es7-react-js-snippets
This plugin will save your time a lot. There are tons of shortcut that make your life easier, such as rcc
to create React Class Component, and rfc
to create React Method Component.
stay hungry, stay foolish
Top comments (1)
Thanks for the post, Bagus~
Would there be a difference between
Method Component
or Function Component?