React hooks were introduced at React Conf October 2018 to introduce state management and side-effects in functional components. They have become a game-changer for a lot of developers. These hooks change the fundamental mindset because of switching from class-based components to functional components with hooks. In this blog post, we will get an overview of these hooks, with the look of how the same logic would be implemented in class-based components.
Why React Hooks?
- Unnecessary Component Refactoring: Previously, only class-based components were used for local state management and lifecycle methods. But later on, class-based components became essential for introducing side-effects such as API requests. If you don’t need a lifecycle hook or state, functional components are used as they are lightweight and elegant. A lot of code is developed using functional-based components. Without hooks, a lot of refactoring is required to use the state or lifecycle method.
With Hooks, there is no need for refactoring. Side-effects and state are directly available in functional components.
2. Complex Components are Hard to Understand: Complex components contain a mix of unrelated code. For example, components might perform some data fetching in componentDidMount and componentDidUpdate. However, the same componentDidMount method might also contain some unrelated logic that sets up event listeners, with cleanup performed in componentWillUnmount. This makes it too easy to introduce bugs and inconsistencies.
Hooks are introduced to solve this by split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data), rather than forcing a split based on lifecycle methods
Rules of Hooks
- Only Call Hooks at the top level: Always use hooks at the top level of your React function. Don’t call hooks inside loops, conditions, or functions. This ensures that all the hooks are called in the same order each time when the functional component renders.
By following these rules, you ensure that all stateful logic in a component is clearly visible from its source code.
List of Hooks
Building Your Own Hooks
Sometimes, we want to reuse some stateful logic between components. Traditionally, there were two popular solutions to this problem: Higher-order components (HOC) and render props. Custom hooks let you do this without adding more components to your tree.
Custom Hooks are more of a convention than a feature. If a function’s name starts with use and it calls other Hooks, we say it is a custom Hook. The useSomething naming convention is how our linter plugin is able to find bugs in the code using Hooks. You can write custom Hooks that cover a wide range of use cases like form handling, animation, declarative subscriptions, timers, and many more.
Further in the series of React Hooks, we will talk in detail about each Hook.