Concepts and Usage
Function component
Receives the props object and returns a React element
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Copy the code
The class components
Inherit react.ponent and create the render function to return the React element
class Welcome extends React.Component { constructor(props) { super(props) } render() { return <h1>Hello, {this.props.name}</h1>; }}Copy the code
The difference between
Amount of code
Fewer functional components
State management
Function components are also stateless and cannot use setState().
Use state in components before React 16.8
- Creating a Class component
- Promote state to the parent component, which is passed to the child component via props
However, React 16.8 updated the Hooks so that you can use the useState Hooks in function components to manage state.
Lifecycle hook
Before React 16.8: You can’t use lifecycle hooks in function components for the same reason that you can’t use state. All lifecycle hooks come from the inherited react.component.
After React 16.8: You can use the useEffect hook to use lifecycle functions.
performance
Functional components perform better than class components, but in modern browsers, the raw performance of closures and classes differs significantly only in extreme scenarios.
Render the difference
How Are Function Components Different from Classes?
Summary and reference
According to the development of React in the past two years, it can be seen that the author attaches more importance to function components, and the React team has mentioned that the performance of function components will be improved in the versions after React.
- The official documentation
- The difference between functional components and class components