乐闻世界logo
搜索文章和话题

What is the difference between a class and functional components in React?

1个答案

1

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.state and this.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> ); } }
  • Functional components:

    • Use the useState Hook 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> ); };

3. Lifecycle Methods

  • Class components:

    • Utilize lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount.
    • Example:
      javascript
      class App extends React.Component { componentDidMount() { console.log('Component did mount!'); } render() { return <div>Check console for lifecycle message.</div>; } }
  • Functional components:

    • Handle side effects using the useEffect Hook, 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>; };

4. Performance Optimization

  • Class components:

    • Reduce unnecessary updates by using shouldComponentUpdate or PureComponent.
  • Functional components:

    • Optimize performance using React.memo or the useMemo and useCallback Hooks.

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 回复

你的答案