I Love ReactJS

Custom Hook from beginner to actual combat

these days we have shared some of React's built-in hook functions, such as useRef, useMemo, useReducer, useImperativeHandle, etc. These built-in hook functions provide great convenience for our development work. In addition to the built-in Hook provided by React, how do we write our own hook functions?

Custom Hook allows us to share logic among multiple components, improving code reusability and maintainability. To customize a hook function, we should follow the following rules:

  1. Custom Hook must start with use .
  2. Custom Hook must be a function, and React's Hook can be used inside the function.
  3. Custom Hook must return data or methods.

the above three rules must be followed, and they are also mentioned in the official React documentation. Let's use a simple counter example to demonstrate how to customize a general hook function.

1. Define the counter hook function

to extract the general logic of a counter into a custom Hook, this hook function should have the following capabilities:

  1. can get the value of the current counter;
  2. can add value to the counter through the hook function;
  3. can reduce the value of the counter through the hook function.

based on these three requirements, we can implement the following custom Hook:

import { useState } from 'react';

// define the return value type of custom Hook
type UseCounterReturnType = [count: number, increment: () => void, decrement: () => void];

// define a custom Hook
export default function useCounter(initialCount: number = 0): UseCounterReturnType {
  // use useState to initialize count state and setCount function
  const [count, setCount] = useState(initialCount);

  // define the increment function to increase the value of the counter
  const increment = () => {
    setCount(count + 1);
  };

  // define the decrement function to reduce the value of the counter
  const decrement = () => {
    setCount(count - 1);
  };

  // return the count, increment and decrement functions as the return values of the custom Hook
  return [count, increment, decrement];
}

We usually maintain custom Hook methods in a separate file. The above sample code implements a useCounter function by TS. Remember the three rules we mentioned above? The function name of the custom Hook must begin with use . In this custom function, we define a state count to record the value of the counter, and two functions to increase the value of the counter and decrease the value of the counter. At the end of the function, put them in an array and return them.

2. Use the counter hook function

it's also very easy to use useCounter above, just call it like any other Hook.

import useCounter from './useCounter';

function MyComponent1(): JSX.Element {
  const [count, increment, decrement] = useCounter(10);

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

In the code

above, we set a default value of 10 for the counter when calling useCounter . When you click the "Increment" button on the page, the counter increases by 1; when you click the "Decrement" button on the page, the counter is subtracted by 1. The value of the current counter is rendered in the H1 tag.

3. Application scenario

Custom Hook has a wide range of application scenarios. Here are some common application scenarios:

  1. processing data logic

    when interacting with the backend interface, we can abstract the data acquisition, processing, caching and so on with the help of custom Hook. For example, you can create a useFetch Hook to get data from the API interface and cache the results to improve page performance.

  2. dealing with form logic

    form validation, formatting, and other logic can also be abstracted. For example, a useForm hook function can be created to handle the form's data and logical validation.

  3. processing view logic

    Some operations on

    UI, such as animation, gesture, and scrolling, can also be abstracted, such as creating a hook function for useSwipe to handle this logic.

  4. deal with side effects

    our common side effects such as timers and subscription events can also be handled with custom hook functions, such as creating a useInterval to handle timer logic.

4. Summary

when creating and using custom Hook, we should choose the appropriate Hook according to specific business or development scenarios. Flexibly mastering the creation and use of custom Hook can greatly improve our development efficiency, as well as code reusability and maintainability.

Exit mobile version