React Components (Functional vs. Class-Based)
Functional Components
A functional component is a JavaScript function that:
- Accepts input through props and returns HTML (JSX).
- Simplifies development by focusing only on presenting UI.
Example of Functional Component:
Greet.jsx
function Greet() {
return <h1>Hello Damilare</h1>;
}
export default Greet;
App.jsx
import React from "react";
import Greet from "./Components/Greet.jsx";
function App() {
return (
<div>
<Greet />
</div>
);
}
export default App;
Class Components
A class component is a JavaScript class that:
- Accepts input through props and maintains internal, private state.
- Contains a render() method that returns HTML (JSX).
Example of Class Component:
Welcome.jsx
import React, { Component } from "react";
class Welcome extends Component {
render() {
return <h1>Class Component</h1>;
}
}
export default Welcome;
Usage in App.jsx:
import React from "react";
import Welcome from "./Components/Welcome.jsx";
function App() {
return (
<div>
<Welcome />
</div>
);
}
export default App;
Comparison: Functional
vs. Class Components
Functional Components
- JavaScript function that returns JSX.
- Stateless by default; uses hooks (e.g., useState, useEffect) for state.
- Simple and ideal for UI-focused logic.
- Keyword 'this' Not required.
- Lightweight Performance and optimized in modern React.
- Great for reusable/presentational components.
Class Components
- JavaScript class that extends Component.
- Can manage internal state without hooks.
- Best suited for complex logic or stateful UI.
- Requires this for referencing properties/methods.
- Heavier and less preferred in modern React.
- More suited for smart/container components.
Advantages of Each Type
Functional Components
- Easier to write and understand.
- No need to deal with this keyword.
- Perfect for components that don't require state management.
- More concise and easier to test.
- With React Hooks, functional components can now handle state and side effects, bridging the gap with class components.
Class Components
- Can maintain private internal state.
- Useful for managing complex logic and component lifecycles.
- Best for older React projects that don't yet use hooks.
Should You Use Functional or Class Components?
In modern React (post v16.8), functional components are the preferred choice because:
- React Hooks (like useState and useEffect) have made functional components equally powerful for state and lifecycle management.
- Functional components are easier to read, write, and debug.
- They provide better performance, especially in rendering.
Class components are still valid but are mainly used in older projects
or for backward compatibility.
Key Takeaway:
- Use functional components whenever possible, especially in new projects.
- Only resort to class components if you're working with legacy code or need specific features unavailable in functional components (rarely the case now).
Progress
Top comments (0)