Teach you to create custom hooks in react

Teach you to create custom hooks in react

1. What are custom hooks

Logic reuse

Simply put, using custom hooks can extract certain component logic into reusable functions. A custom hook is a Javascript function that calls other hooks starting from use .

2. When not using custom hooks

Example 1: When our entire page needs to obtain the coordinates of the user's mouse movement, without using the hook code, we can write

  const [position, setPosition] = useState({
    x: 0,
    y: 0
  })
  useEffect(() => {
    const move = (e) => {
      setPosition({ x: ex, y: ey })
    }
    document.addEventListener('mousemove', move)
    return () => {
      document.removeEventListener('mousemove', move)
    }
  }, [])
  return (
    <div>
      x:{position.x}
      y:{position.y}
    </div>
  )

Example 2: When we have an image on our page that follows the mouse, we can also write it like this without using the hook code:

const [position, setPosition] = useState({
    x: 0,
    y: 0
  })
  useEffect(() => {
    const move = (e) => {
      setPosition({ x: ex, y: ey })
    }
    document.addEventListener('mousemove', move)
    return () => {
      document.removeEventListener('mousemove', move)
    }
  }, [])
  return (
    <div>
      <img
        src={img}
        style={{
          position: 'absolute',
          top: position.y,
          left: position.x,
        }}
        alt=""
      />
    </div>
  )

Obviously, the above two examples have different presentation effects, but the logic codes used are mostly the same. We can use hooks to reuse the logic codes.

3. Use custom hook

We extract the reusable logic code from the above two examples and create a new file called useMousePosition

import { useState, useEffect } from 'react'
export default function useMousePosition() {
  const [position, setPosition] = useState({
    x: 0,
    y: 0
  })
  useEffect(() => {
    const move = (e) => {
      setPosition({ x: ex, y: ey })
    }
    document.addEventListener('mousemove', move)
    return () => {
      document.removeEventListener('mousemove', move)
    }
  }, [])
  return position
}

We extracted this functionality in the useMousePosition function. Now we can import it wherever we want to use it!

Finally, use it like a normal function

  const position = useMousePosition()
  return (
    <div>
      x:{position.x}
      y:{position.y}
    </div>
  )

Obviously, the amount of code is reduced

This is the end of this article about creating custom hooks in react. For more relevant react custom hooks content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • ReactHooks batch update state and get route parameters example analysis
  • React Hook: How to use Effect Hook
  • Understand react-hooks and example code in three minutes
  • Introduction to 10 Hooks in React
  • React Hooks Detailed Explanation
  • React Hook: How to use State Hook

<<:  Example of using docker compose to build a consul cluster environment

>>:  The use of textarea in html and common problems and case analysis

Recommend

JS asynchronous execution principle and callback details

1. JS asynchronous execution principle We know th...

Specific use of pthread_create in linux to create threads

pthread_create function Function Introduction pth...

MySql5.7.21 installation points record notes

The downloaded version is the Zip decompression v...

What to do if you forget your Linux/Mac MySQL password

What to do if you forget your Linux/Mac MySQL pas...

Detailed explanation of how to mount remote file systems via SSH on Linux

Features of SSHFS: Based on FUSE (the best usersp...

Detailed steps to install JDK and Tomcat in Linux environment

Table of contents 1. Install JDK Manual Installat...

Application of HTML and CSS in Flash

Application of HTML and CSS in Flash: I accidental...

MySQL configuration SSL master-slave replication

MySQL5.6 How to create SSL files Official documen...

jQuery realizes the picture following effect

This article shares the specific code of jQuery t...

Let you understand the deep copy of js

Table of contents js deep copy Data storage metho...

MySQL 8.0.20 installation and configuration method graphic tutorial

MySQL download and installation (version 8.0.20) ...

Vue recursively implements custom tree components

This article shares the specific code of Vue recu...