4 ms·
Class components don't scale or compose well. You have a fixed number of lifecycle methods, and each new behavior you add to your component has to be split up a
by phailhaus 3y ago
Class components don't scale or compose well. You have a fixed number of lifecycle methods, and each new behavior you add to your component has to be split up across those methods and mixed in with everything else. This means that your components are going to get much harder to debug and maintain as they get larger, and it's very difficult to split out common behavior in a form that's easy to mix in to existing components. That's the advantage of hooks: each hook can be defined by a single function that manages its entire lifecycle in isolation, and can be dropped into any component with a single line.
> that means my component function is going to be executed several times
Who cares? That shouldn't be your concern. All you should think is "this effect will get called every time these values change. Am I okay with that?" React will handle running your component function consistently with the right state, you just have to worry about whether your component is rendering the right thing given that state, and running the right effects. React handles correctness. You don't have to remember "oh whenever I update this state, I have to run this other function to make sure everything is in sync" as with class-based components. Because invariably, another engineer will come along, make some changes, and forget to call that function. Now you have a really tricky bug to find that depends on internal state.
This is why hooks have caught on: you can truly write pure declarative components (most of the time) and not worry about execution order or dependencies at all. The tradeoff is that you have to think very...reactively. It's definitely a different mindset, but it means that there's a whole class of bugs you never have to think about because React handles it.