Thoughts on Hooks
I spent some time this week getting up to speed on Hooks in React. Hooks are a controversial evolution of React component development. Hooks encourage a strong focus on functional components that can take advantage of state and side effects, diminishing the need for classes and lifecycle methods. When they were announced, the reaction was split: some of us were excited and others felt React was moving in the wrong direction.
Hooks may be the next big thing but they won’t replace anything today. I migrated a few class-based components in our codebase at work with mixed results. Generally, components look cleaner after transitioning from a class, but there’s cognitive overhead in migrating from lifecycle methods. Here's an incomplete list of gotcha's:
- Some lifecycle methods have no comparable Hook to replace them yet.
- Classes that need to accept refs are poor candidates for Hooks.
- If you're used to not thinking about comparing props because you use
React.PureComponent, you'll need to pay more attention to memoizing your components and Hooks.
For now, I’d recommend against efforts to completely refactor existing classes to use Hooks. React docs recommend gradual adoption and there's no sign that classes are going away. So there's no rush to adopt Hooks right away.
Using Hooks felt like working in a different framework. I have mixed feelings about this. Hook-based components require a slightly different mental model - one where you worry less about the lifecycle stages. For most teams, especially teams maintaining a lot of class-based components, this is a bit of a non-starter. However, new components and new projects will definitely benefit from Hooks.
Writing components with Hooks results in cleaner components, clearer separation of concerns, and enables reusability of stateful logic. These are big wins. On the whole, I like Hooks. I can see how they could become the future of React components.