Difference between class component and functional component :

In React.js, there are two main types of components: class components and functional components. Both types of components serve the same fundamental purpose,

Class Component :

  • Class components are the older way of defining components in React.
  • They are ES6 classes that extend the React.Component base class.
  • Class components have a render method, which returns the JSX (JavaScript XML) that represents the component's UI.
  • You can use lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount to manage component behavior and side effects.
  • Class components can also hold and manage component states using the setState method.

example :

import React, { Component } from 'react';
class MyComponent extends Component { render() { return <div>Hello, I'm a class component!</div>; } }


Functional component :

  • Functional components are a more recent addition to React and have been enhanced with React Hooks in newer versions.
  • They are just JavaScript functions that take props as input and return JSX.
  • Functional components are often used with hooks like useState, useEffect, and useContext to manage state and side effects.
  • They are simpler and more concise compared to class components.

example:

import React from 'react'; function MyComponent() { return <div>Hello, I'm a functional component!</div>; }



 


Comments

Popular posts from this blog