React Function and Class Components
Source: Dev.to
Function Components
In React, function components are defined as simple JavaScript functions that receive props (properties from parent components) as arguments and return JSX (a syntax extension for defining UI elements).
- Easier to write and understand, especially for simpler components.
- Initially had no access to lifecycle methods or state, but since React 16.8 they can use hooks (
useState,useEffect, etc.) to handle state and side effects.
Example
function Greeting(props) {
return
## Hello, {props.name}!
;
}
Class Components
Class components are defined as JavaScript classes that extend React.Component.
- Provide built‑in lifecycle methods (e.g.,
componentDidMount). - Manage state directly via
this.stateandthis.setState. - Suitable for components with more complex behavior or interactions with external data sources.
Example
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
You clicked {this.state.count} times
Click me
);
}
}
Additional Samples
Function component
function Welcome(props) {
return
## Hello, {props.name}
;
}
Class component
class Welcome extends React.Component {
render() {
return
## Hello, {this.props.name}
;
}
}
Demo
import React from "react";
import ReactDOM from "react-dom";
function Welcome(props) {
return
## Hello, {props.name}
;
}
class WelcomeClass extends React.Component {
render() {
return
## Hello, {this.props.name}
;
}
}
const element = ;
const elementClass = ;
ReactDOM.render(element, document.getElementById("root"));
ReactDOM.render(elementClass, document.getElementById("root-class"));
Choosing the Right Component
- Simple UI: Use function components for basic rendering without state or lifecycle needs.
- Complex behavior or state: Use class components when you need explicit lifecycle methods or more intricate state management.
- Modern React: Since React 16.8, function components with hooks are often preferred for their simplicity and future‑proof nature.
Additional Considerations
- Performance: Function components are generally slightly faster, especially for simple cases.
- Readability: Hooks can lead to cleaner, more concise code compared to class syntax.
- Community preference: The React community currently favors function components with hooks, and most new libraries and tutorials follow this trend.
Conclusion
The best choice between function and class components depends on the specific needs and complexity of your component. Evaluate factors such as state management, lifecycle requirements, and team conventions, then experiment to find the approach that works best for your project.
Happy coding! 🔥