Home > Article > Web Front-end > React Components (Class-based vs Functional)
React components are the building blocks of any React application. They allow you to split the UI into independent, reusable pieces that can be managed and rendered separately. React components come in two main types: Functional Components and Class Components.
Functional Components
Functional components are simpler and are written as JavaScript functions. They take props (input data) as an argument and return JSX, which describes what the UI should look like. As of React 16.8, functional components can also handle state and side effects using hooks like useState and useEffect.
import React, { useState } from 'react'; const Welcome = (props) => { const [count, setCount] = useState(0); return ( <div> <h1>Hello, {props.name}!</h1> <p>You've clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ); }; export default Welcome;
Class Components
Class components were the original way to write components in React. They extend the React.Component class and must include a render() method that returns JSX. Class components can have their own state and lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
import React, { Component } from 'react'; class Welcome extends Component { constructor(props) { super(props); this.state = { count: 0 }; } handleClick = () => { this.setState({ count: this.state.count + 1 }); } render() { return ( <div> <h1>Hello, {this.props.name}!</h1> <p>You've clicked {this.state.count} times</p> <button onClick={this.handleClick}>Click me</button> </div> ); } } export default Welcome;
Key Concepts:
Hooks (for functional components):
React encourages the creation of small, reusable components that can be combined to form larger applications, keeping the codebase modular and easier to maintain.
The above is the detailed content of React Components (Class-based vs Functional). For more information, please follow other related articles on the PHP Chinese website!