Class Components

Class Components

Table of contents

No heading

No headings in the article.

A class component requires you to extend from react component and create a render function that returns a react element. A bit confusing? Let’s take a look at a simple example.

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

In class components, the render method will be called, whenever the state of the components changes. On the other hand, the Functional components render the UI based on the props. Class Components should be preferred whenever we have a requirement with the state of the component.

another example of a class component

class Person extends Component {
 constructor(props){
 super(props);
 this.state = {
 name: “Ravindra”;
 }
 }

 render() {
 return (
 <div>
 <h1>Hello {this.state.name}</h1>
 </div>
 );
 }
}
export default Person;

super(props) that directly overwrites this.state

functional component

First of all, the apparent difference is the syntax. Like in their names, a functional component is just a plain JavaScript function that returns JSX.which accepts props as an argument and returns a React element.

function App() {
  return (
    <div>
      <h2>Hello React!</h2>
    </div>
  );
}

Functional components are much easier to read and test because they are plain JavaScript functions without state or lifecycle hooks You end up with less code.