Class components and function components

No life cycle function, no need to access this, the code is simpler

The class components:

  • You need to write a lot of periodic functions, and you need this to access custom events and some instance apis

Function components:

  • You don’t have to write life cycle functions and this

It is difficult to reuse state logic between components

The class components:

  • React does not provide a way to “attach” reusable behavior to components.

  • In class components, providers, consumers, render props and higher-order components can be used to reuse state logic. The component structure needs to be reorganized to form nested components and code, making the code difficult to understand.

Function components:

  • Hooks allow you to reuse state logic without modifying the component structure.

Complex components are easier to understand

The class components:

  • Class components are increasingly overwhelmed with state logic and side effects. Each life cycle often contains some unrelated logic. For example, components often get data in componentDidMount and componentDidUpdate. However, the same componentDidMount may also contain a lot of other logic, such as setting up event listeners that need to be cleared later in componentWillUnmount.

  • Code that is related and needs to be modified against each other is split, while completely unrelated code is grouped together in the same method. This is very buggy and leads to logical inconsistencies.

  • It is impossible to break the components down to smaller granularity because state logic is everywhere. Not good for unit testing.

Function components:

  • Hooks break down the interrelated parts of a component into smaller functions (such as setting up subscriptions or requesting data) rather than enforcing partitioning by lifecycle. You can also use Reducer to manage the internal state of components and make them more predictable.

More react philosophy

The class components:

  • The props and state of the subcomponent may be different from what the subcomponent wants to use. You need to do a deconstruction to save the value of this.props or this.state to ensure that the rendering is correct.

  • Because the props themselves do not change, for a function component, the props fetched will not change with this.

Function components:

  • The functional component gets the values required by Render.

  • The React design concept is that the UI is conceptually a render function of the current application state, and our render is essentially a specific render with specific props and states.