As it turns out you shouldn't use them because they were essentially deprecated a long time ago. But in terms of comparing the merits in a more theoretical sense, there are simply tradeoffs between the two.
Reacts insistence at the time on everyone should use hooks was hands down one of the dumbest things I’ve seen in all my time.
Not only was it on extremely shaky grounds technically but now you have huge swaths of developers have this extremely React specific mental model of building apps that translates poorly to almost everything else out there.
There is a reason why almost nobody else out there followed that trend. Classes are actually the ideal abstraction for building a component based on UI.
import React from 'react';
class WindowWidth extends React.Component {
state = { width: window.innerWidth };
handleResize = () => {
this.setState({ width: window.innerWidth });
};
componentDidMount() {
window.addEventListener('resize', this.handleResize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
}
render() {
return <p>Window width: {this.state.width}px</p>;
}
}
export default WindowWidth;
and this import React, { useState, useEffect } from 'react';
function WindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
return <p>Window width: {width}px</p>;
}
export default WindowWidth;
Whats going on here? I see it adds and removes a resize event listener… okay, when?What happens with the function it returns?Why do I need to pass in an empty array? What could even go in there? What happens if I omit it (it is empty).
Where is the unmounting and mounting? What order do things happen in and when?
These have answers of course. The function runs according to the dependency array (prop, state, etc) and just on mount if empty. And the callback runs on unmount, if any. But you have to learn them. Before you do, it's magic. And when you step away, you have to re-learn it. And when it gets a bit more complicated, you're going to have to sit down and learn it better.