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.Componentbase class. - Class components have a
rendermethod, which returns the JSX (JavaScript XML) that represents the component's UI. - You can use lifecycle methods like
componentDidMount,componentDidUpdate, andcomponentWillUnmountto manage component behavior and side effects. - Class components can also hold and manage component states using the
setStatemethod.
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, anduseContextto 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
Post a Comment