In React, class components and functional components are two primary forms of components, each with distinct characteristics in implementation and functionality:
1. Definition
-
Class components:
- Defined using ES6 class syntax.
- Must extend
React.Component. - Example:
javascript
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
-
Functional components:
- Defined using JavaScript functions, which can be regular functions or arrow functions.
- Since React 16.8, functional components can manage state and other React features using Hooks.
- Example:
javascript
const Welcome = ({ name }) => <h1>Hello, {name}</h1>;
2. State Management
-
Class components:
- Manage state using
this.stateandthis.setState. - Example:
javascript
class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <p>{this.state.count}</p> <button onClick={this.increment}>Increment</button> </div> ); } }
- Manage state using
-
Functional components:
- Use the
useStateHook to manage local state. - Example:
javascript
const Counter = () => { const [count, setCount] = useState(0); const increment = () => { setCount(count + 1); }; return ( <div> <p>{count}</p> <button onClick={increment}>Increment</button> </div> ); };
- Use the
3. Lifecycle Methods
-
Class components:
- Utilize lifecycle methods such as
componentDidMount,componentDidUpdate, andcomponentWillUnmount. - Example:
javascript
class App extends React.Component { componentDidMount() { console.log('Component did mount!'); } render() { return <div>Check console for lifecycle message.</div>; } }
- Utilize lifecycle methods such as
-
Functional components:
- Handle side effects using the
useEffectHook, which can mimic lifecycle behavior. - Example:
javascript
const App = () => { useEffect(() => { console.log('Component mount/update'); return () => { console.log('Component will unmount'); }; }, []); return <div>Check console for lifecycle message.</div>; };
- Handle side effects using the
4. Performance Optimization
-
Class components:
- Reduce unnecessary updates by using
shouldComponentUpdateorPureComponent.
- Reduce unnecessary updates by using
-
Functional components:
- Optimize performance using
React.memoor theuseMemoanduseCallbackHooks.
- Optimize performance using
Summary
Although both component types can be used to build React applications, functional components are increasingly preferred for their simplicity and support for Hooks. In particular, after the introduction of Hooks, functional components have become nearly as capable as class components, and in some aspects, they are even more elegant and straightforward.
2024年7月15日 09:54 回复