React basic 4 — Class Based Component and Lifecycle Methods
In contrast to the functional component from the previous post (React basic 3 — Reusable Functional Components), if your component should manage states properly, class component may be the way to go. Class component comes with a built-in lifecycle that allows you to manipulate your component at different phases. This post explains how to create a class-based component by going over the most fundamental, constructor() and render() lifecycle methods first.
Create the first class-based component
Step 1. Declare class and extend React.Component
The structure of class-based component is similar to the functional component. Instead of declaring with const for functional components, we extend React.Component subclass to declare a class. Below is an example of how a simple functional component could be refactored into a class-based component.
Functional Component
const App = () => { return(
<h1>Hello!</h1>
);};
Class-based Component
class App extends React.Component { render() { return (
<h1>Hello!</h1>
);