Functional and Class Components in React

Functional and Class Components in React

Functional vs Class Components in React

  • a component represents the part of the user interface
  • components are reusable and can be used anywhere in the user interface

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

Class component

A class component is a JavaScript class that extends React.Component which has a render method. 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