Functional Components Vs. Class Components in ReactJS

ReactJSWeb DevelopmentFront End Technology

Functional Components or stateless components are the most widely used type of components with a basic syntax of JavaScript Functions that return the JSX code or the HTML code.

They are called as stateless components because they accept the data and display it accordingly and are mainly responsible for the rendering of the UI.

Example

import React from ‘react’;

const App=()=>{
   return (
      <div>
         <h1>TutorialsPoint</h1>
      </div>
   )
}
export default App

Output

Class based or stateful Components are the ES6 classes that extend the component class of the react library. They are known as stateful components because they are responsible for the implementation of the logic. It has different phases of the React lifecycle including rendering, mounting, updating and unmounting stage.

Example

import React from 'react';

class App extends React.Component{
   render() {
      return (
         <div>
            <h1>TutorialsPoint</h1>
         </div>
      )
   }
}
export default App

Output

Difference between functional and class-based component

Class-based ComponentsFunctional Components
It must have a render() method.It doesn’t have a render() method.
React lifecycle methods (like componentDidMount, etc.) are used.React hooks are there to be as a better alternative to the traditional React lifecycle methods.
It has more code and hence, is less readable.It has less code and hence, is more readable.


raja
Published on 18-Mar-2021 10:43:50
Advertisements