Member-only story
Differences between Functional Components and Class Components with a Counter App Example
2 min readNov 20, 2024
Functional Components
Functional Components are some of the more common components that will come across while working in React. They are Javascript functions.
const Car = () => {
return <h2>Hi, I am also a car!</h2>
}
- Functional component is just a plan JavaScript pure function that accepts props as an argument and returns a React element (JSX).
- There is no render method used.
- It runs from top to bottom and once the function is returned it can’t be kept alive.
- AKA Stateless components. It accepts data and displays them. They’re responsible for rendering UI.
- React lifecycle methods (like componentDidMount) cannot be used here.
- Constructors are not used.
- Hooks can be easily used in functional components to make them stateful.
const [name, setName] = React.useState(" ");
How to create Counter using Functional Components
import React, { useState } from "react";
const FunctionalComponent = () => {
const [count, setCount] = useState(0);
const increase = () => {
setCount(count+1);
}
return (
<div style = {{margin: "50px"}}>
<h1>Welcome!</h1>
<h3>Counter App</h3>
<h4>{count}</h4>
<button…