React Components: Class vs Functional - Why Modern React Prefers Functions ??
Remember when React components were all about classes? Fast forward to 2024, and functional components have become the standard. Let's dive into this evolution and understand why the shift happened!
The Evolution Journey ??
Class Components (The Past)
jsx
class Welcome extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<h1>Hello, {this.props.name}</h1>
<button onClick={this.handleClick}>
Clicked {this.state.count} times
</button>
</div>
);
}
}
Functional Components (The Present)
jsx
function Welcome({ name }) {
const [count, setCount] = useState(0);
return (
<div>
<h1>Hello, {name}</h1>
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
</div>
);
}
Why Functional Components Win ??
1. Simplicity
2. Hooks Power
jsx
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchUser(userId)
.then(data => {
setUser(data);
setLoading(false);
});
}, [userId]);
if (loading) return <Loader />;
return <Profile user={user} />;
}
领英推荐
3. Better Performance
4. Reusability Through Custom Hooks
// Custom Hook
function useWindowSize() {
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight
});
useEffect(() => {
const handleResize = () => {
setSize({
width: window.innerWidth,
height: window.innerHeight
});
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
// Using the custom hook
function ResponsiveComponent() {
const { width, height } = useWindowSize();
return <div>Window size: {width} x {height}</div>;
}
When to Still Use Class Components? ??
The Future is Functional ??
jsx
// Modern React Pattern
function Counter() {
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount(c => c + 1), []);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<button onClick={increment}>
Count: {count}
</button>
);
}
?? Weekly Challenge
jsx
class Timer extends React.Component {
state = { seconds: 0 };
componentDidMount() {
this.interval = setInterval(() => {
this.setState(state => ({
seconds: state.seconds + 1
}));
}, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <div>Seconds: {this.state.seconds}</div>;
}
}
Share your solution in the comments!
#React #WebDevelopment #JavaScript #Programming #FrontEnd #ReactHooks #LinkedInLearning
"MEAN Stack Developer | Full-Stack Web Applications | Specialist in E-commerce, HRMS & Real-time Systems"
2 个月Very helpful