Functional components and class-based components are two different ways of creating components in React.
Functional components are simpler and easier to understand. They are basically JavaScript functions that take in props as arguments and return JSX (JavaScript XML) elements. Functional components are stateless, meaning they don’t have their own internal state. They are mainly used for presenting UI and receiving props from parent components.
Here is an example of a functional component in React:
function FunctionalComponent(props) { return <div>{props.message}</div>; }
Class-based components, on the other hand, are more powerful and flexible. They are created by extending the base React.Component
class and implementing its methods. Class-based components have their own internal state, which can be modified using the setState
method. They also have lifecycle methods like componentDidMount
and componentDidUpdate
that can be used for performing actions at specific points in the component’s lifecycle.
Here is an example of a class-based component in React:
class ClassBasedComponent extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } componentDidMount() { console.log("Component mounted"); } componentDidUpdate() { console.log("Component updated"); } render() { return <div>{this.state.count}</div>; } }
In summary, functional components are simpler and stateless, while class-based components are more powerful and have their own internal state. The choice between them depends on the complexity and requirements of the component you are building.