-->
When I first tried out React a couple years ago, I learned Class Components first, but now, it appears that the industry has shifted in favor of Functional Components. Since Iāve been diving back into React, Iāve been wondering: Whatās the difference? What why this shift? Hereās what I found out.
Functional components are a type of component in React that are primarily defined as JavaScript functions. They are also known as āstateless functional componentsā because they donāt have their own internal state management; instead, to manage state, they use hooks.
import React from 'react';
interface GreetingProps {
name: string
}
const Greeting: FC<GreetingProps> = ({ name }) => {
return <h1>Hello, {name}!</h1>;
};
export default Greeting;
Class Components Class components can have additional methods and lifecycle methods that handle various aspects of the componentās behavior. For example, you can define the componentDidMount() method to execute code after the component is mounted in the DOM, or the componentDidUpdate() method to perform actions when the componentās props or state change. import React, { Component } from āreactā;
class Example extends Component { componentDidMount() { console.log(āComponent mounted!ā); }
render() { return
export default Example;
Class components provide more explicit control over the componentās lifecycle and state management compared to Functional Components. However, with the introduction of React Hooks, many of the same capabilities can be achieved using functional components with simpler and more concise code.
I think Functional Components are definitely making my development experience a lot easier, as it removes the needs for managing internal state and functions. Thatās an abstraction Iām definitely glad we shifted towards, although I would like to get a bit more familiar with Class Components for the sake of better understanding what goes on underneath the hood.