In React, there are two main ways to define components: class components and function components.
Class components are defined as classes that extend the React.Component class. They are able to maintain state and lifecycle methods such as componentDidMount and componentDidUpdate. Class components also allow you to define methods for handling user events and rendering the component.
Here is an example of a simple class component:
Function components, on the other hand, are defined as JavaScript functions that return React elements. They are simpler and more lightweight than class components, and are typically used for components that do not require state or lifecycle methods. Function components are also known as "stateless" or "dumb" components.
Here is an example of a simple function component:
In recent versions of React, function components can also define state and lifecycle methods using the useState
and useEffect
hooks, making them more versatile and powerful than before.