Basic Differences
- Syntax: Class vs Function
- Lifecycle
- State - In-built in classes
- Error Boundary - Only in classes
- Hooks - Only functional components can use hooks
- Data Fetching -
componentDidMount
vsuseEffect
Class Components
class MyComponent extends React.Component<MyComponentProps, State> { render = () => { return <div>Hello World!</div>; } }
A class component is declared using a class. It inherits from the Component
class in the react
library. In TypeScript
, it's a generic class, meaning it takes two types as the type of properties passed to this component, Props
, and the type the component's state will take, State
.
Every class component must have a render
function - the value it returns will be displayed to the user. Besides that, there are several functions that can be overridden - these are called lifecycle methods of the component. They are executed at different stages of the component's life - for example, before rendering, after rendering, during prop changes, etc.
A class component can act as an Error Boundary
, meaning it can handle the event of an error occurring in any of its descendant components. This is achieved by overriding the getDerivedStateFromError
and/or componentDidCatch
methods.
Class components can also have their own internal state, modifying which triggers a re-render of the component (similar to changing props).
More information about component lifecycle methods can be found here. More information about error boundaries here.
Functional Components
Their syntax is nothing but a function. They use JSX syntax, similar to the render
function in class components.
The lifecycle of functional components is handled through hooks - special functions designed for use in functional components. They allow handling state, events, capturing the component's render time, etc.
A functional component cannot act as an Error Boundary
.
As it is a function, its entire body is executed every time the higher element in the tree is re-rendered - regardless of whether props or the component's state changes. Therefore, optimizing code and function calls using memoization is important.
const MyComponent: React.FC<MyComponentProps> = (props) => { return <div>Hello World!</div>; }
More information about the basic functional component can be found here.