In React, components are the building blocks of user interfaces. There are two main types of components: class components and functional components. Here's an overview of each:
1. Class Components:
- Class components are ES6 classes that extend from
React.Component
and can have state and lifecycle methods. - They are typically used when the component needs to have state, handle lifecycle events, or use other advanced features such as context or refs.
- Class components are defined using the class keyword.
- Here's an example of a class component:
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
export default MyComponent;
2. Functional Components:
- Functional components are simple JavaScript functions that take props as arguments and return React elements.
- They are typically used for presentational or stateless components, where the component doesn't need to manage its own state or lifecycle.
- Functional components are defined using arrow functions or regular functions.
- Here's an example of a functional component:
import React from 'react';
const MyComponent = (props) => {
return (
<div>
<p>Hello, {props.name}!</p>
</div>
);
};
export default MyComponent;
- With React 16.8, functional components can also use Hooks, which allows them to manage state and use lifecycle features previously only available in class components.
- Here's an example of a functional component using Hooks:
import React, { useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
};
export default MyComponent;
In this blog class components are ES6 classes that provide more features like state and lifecycle methods, while functional components are simple JavaScript functions that are typically used for presentational purposes and can use Hooks to manage state and lifecycle in modern React applications.
Array methods in react.js
Fragment in react.js
Conditional rendering in react.js
Children component in react.js
use of Async/Await in react.js
Array methods in react.js
JSX in react.js
Event Handling in react.js
Arrow function in react.js
Virtual DOM in react.js
React map() in react.js
How to create dark mode in react.js
How to use of Props in react.js
Class component and Functional component
How to use of Router in react.js
All React hooks explain
CSS box model
How to make portfolio nav-bar in react.js
Top comments (0)