What Is React Hook?

February 14, 2023

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

Despite the fact that most React development in recent years has been done using Hooks, Hooks only appeared in React 16.8. They are also a common topic in job interviews. This article summarizes:

  • What are Hooks?
  • What problems do Hooks solve?
  • What are the rules of Hooks?
  • What are some commonly used Hooks?

What Are Hooks?

Before React 16.8, if we wanted to use lifecycle methods or state, we had to use class components. However, the introduction of React Hooks allows us to use React's functionality and state even with functional components. In React, a function that starts with use is called a Hook. Some Hooks are built-in React features, such as useState and useEffect, but we can also create our own Hooks. Hooks are more strict than regular functions and have some rules that need to be followed, which we will discuss below.

What Problems Do Hooks Solve?

The React team developed Hooks to address the following three issues:

  • Stateful logics are difficult to reuse between class components.

    In class components, React does not provide a way to add repeated logic to a component. Developers may use render props or higher-order components to achieve this, but this can result in the need to restructure the component, making the code harder to read and understand (referred to as "wrapper hell" in the React documentation). One of the main problems that Hooks solve is to allow the sharing of stateful logic.

    With Hooks, developers can extract state-related logic from a component and reuse it independently. We can also reuse the same logic in a component without having to restructure it. For example, if an application needs to detect page scrolling and trigger certain functions based on the scroll, we can write a useScroll Hook and share its state logic across different pages. Currently, there are many Hook libraries available in the React community that provide a variety of reusable Hooks.

  • Before Hooks, the logic in complex components became increasingly difficult to understand.

    As class components become more complex, we may need to add many unrelated logics in the same lifecycle method. For example, componentDidMount may need to handle both data fetching and event listener logic, which is not only hard to understand but also difficult to maintain. In many cases, these components cannot be broken down into smaller ones.

    To address this problem, Hooks allow us to break down a component into smaller functions, rather than splitting it up based on lifecycle methods. For example, in the previous example, data fetching and event listener logic can be handled separately in the same component using two useEffect hooks, or they can be split into two custom hooks. By breaking down components in this way, we can make them easier to understand and maintain.

  • Classes are difficult for developers to understand.

    The React team found that classes could be a major obstacle to learning React, as the concept of classes in JavaScript and other languages can be quite different. To address this problem, Hooks allow developers to use more of React's features without the need for classes. Conceptually, React components have always been closer to functions. Hooks contain functions, but do not sacrifice the practical spirit of React, and do not require special knowledge of complex functional or reactive programming.

Rules of Hooks

  1. Hooks can only be used at the top level

    Hooks cannot be used in loops, if/else statements, or nested functions such as map. We need to ensure that they are always used at the top level of the React function and before any return statements. In the article "Why Do We Need To Call React Hook at the Top Level? Why Can’t We Call It Inside a Loop or Condition?" we discuss the reasons behind this, which is also a commonly asked interview question.

  2. Hooks can only be used in React functions.

    Hooks cannot be used in regular JavaScript functions. They can only be used in the following scenarios:

    • In React functional components
    • In other Hooks used in custom Hooks

Commonly Used Hooks

useState

Used to define and save the state of a component. It returns an array containing two values: the current state value and a setter function. We can update the state value using the setter function and trigger a re-render.

useEffect

Used to handle side effects such as fetching APIs, tracking, and setInterval(). We need to pass two parameters to useEffect. The first is a setup function, which represents the side effect code we want to execute. If we need to clean up this side effect, we need to return a cleanup function at the end. The second parameter is an array of variables that the side effect code will depend on.

useLayoutEffect

Similar to useEffect, the only difference is the timing of execution. useLayoutEffect is executed after the DOM is updated, while useEffect is executed after the render is complete.

useReducer

Another state management Hook that can be used as an alternative to useState. It accepts two parameters: a reducer and an initial value. It returns two values: the current state value and the dispatch method. When the state management logic becomes more complex, it is usually recommended to use useReducer instead of useState.

useCallback

Used to cache functions between re-renders. It returns a memoized callback function that will only update when the dependency changes. This method is usually used for performance optimization.

useMemo

Used to cache the calculation results between re-renders. It takes a creation function and a dependency list. The creation function needs to return a value, and the value will only update when the dependency changes. This method is usually used for performance optimization.

useRef

Used to store values that do not need to be rendered. It returns a mutable ref object, and the .current attribute is initialized to the parameter value (initialValue).


☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee