01 December 2024
React components are the building blocks of React applications. They allow developers to break the UI into reusable, independent pieces.
Aspect | Functional Components | Class Components |
---|---|---|
Definition | Plain JavaScript functions that return JSX. | ES6 classes that extend React.Component . |
State | Uses the useState and useEffect hooks (introduced in React 16.8). | Uses this.state for managing state. |
Lifecycle Methods | Replaced by hooks like useEffect . | Explicit lifecycle methods like componentDidMount . |
Syntax | Simpler and more concise. | More verbose due to class structure. |
Performance | Generally lighter and faster. | Slightly heavier because of class overhead. |
Example | ||
Functional Component: | Class Component: | |
```jsx | ```jsx | |
function Greet() { | class Greet extends React.Component { | |
return <h1>Hello</h1> ; | render() { | |
} | return <h1>Hello</h1> ; | |
``` | } |
Creating a Functional Component
// Greet.jsx
function Greet() {
return <h1>Hello, World!</h1>;
}
export default Greet;
Creating a Class Component
// Welcome.jsx
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1>Welcome to React!</h1>;
}
}
export default Welcome;
Named Exports You can export multiple components from a file:
// Greetings.jsx
export function Hello() {
return <h1>Hello!</h1>;
}
export function Goodbye() {
return <h1>Goodbye!</h1>;
}
import Greet from './Greet';
function App() {
return (
<div>
<Greet />
</div>
);
}
export default App;
import { Hello, Goodbye } from './Greetings';
function App() {
return (
<div>
<Hello />
<Goodbye />
</div>
);
}
export default App;
import { Hello as Hi } from './Greetings';
function App() {
return <Hi />;
}
export default App;
import Greet from './Greet';
function Header() {
return (
<header>
<Greet />
<h2>This is a header</h2>
</header>
);
}
export default Header;