Components are self-sustaining, independent micro-entities that describe a part of the UI and can break down the UI of the application into smaller components, each with its own code, structure, and API. In simple terms, components allow you to split the UI into independently reusable code snippets and think about each snippet independently.
In React, components are mainly divided into two categories based on their state: stateless components and stateful components. Generally, components created using the class
keyword, with their own private data this.state
and lifecycle functions, are stateful components, while components created using function
with only props
and without their own private data and lifecycle functions are stateless components.
A stateless component, also known as a Stateless Component
, is the most basic form of component, as it is purely for static display without the influence of state. Typically, it is the first category of components developed in various UI libraries, such as buttons, labels, input boxes, and so on. Its basic structure consists of properties props
and event function calls. Due to the absence of state updates, this type of component has the strongest reusability. Since stateless components do not have their own state
and lifecycle functions, they exhibit high runtime efficiency.
DOM
by accepting props
.extends
or constructor
-like code, making the syntax more concise.ref
, but can use React.forwardRef
to wrap and then pass a ref
.this
keyword. In class declarations of ES6
, functions often need to bind the this
keyword to the current scope, but due to the nature of functional declaration, this is no longer necessary.React
does not need to perform specific checks or memory allocations, ensuring better performance.In essence, if a component does not need to manage state
and only serves for pure display, it can be defined as a stateless component.
For such stateless components, using a functional declaration makes the code more readable and greatly reduces the amount of code. Using arrow functions can make the code more concise.
A stateful component, also known as a Stateful Component
, is built on the foundation of stateless components. When a component internally contains a state
that changes with events or external messages, it becomes a stateful component. Stateful components usually have lifecycles to trigger state updates at different times. This type of component is commonly used in writing business logic, and the number of component states and the lifecycle mechanism vary depending on different business scenarios.