Hacker News new | ask | show | jobs
by superice 2245 days ago
The biggest difference is that the class based components are an older iteration of the API into React, one that lies closer with how React internally works (or worked), but one that is not necessarily useful for writing correctly working components.

Say you have a component that renders some data it fetches from the backend, and it received the ID via a prop. In a class based component you might be inclined to write the fetching logic in the componentDidMount or maybe the constructor. However, if you change the ID you feed the component, the component will update instead of being recreated. In the naive class based version it won't refetch the data, and won't behave correctly. With useEffect hooks you don't really care anymore, you can reason about side effects in the same declarative way. You express the fact that fetching new data is a dependency of the prop changing, which holds true both on first render and later on update.

The hooks API fixed a handful of these 'mistakes' that were still present in the class based API. I agree that the syntax might look awkward at first, but the hooks API is much better thought out than the class based one.

(Some anecdata: almost any component that I rewrote in hooks-style has been halved in number of lines of code, the concepts have been much less spread out over the file. See this tweet for an example: https://twitter.com/threepointone/status/1056594421079261185)