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

Detailed explanation of the loop form item example in Vue

Sometimes we may encounter such a requirement, th...

JavaScript Factory Pattern Explained

Table of contents Simple Factory Factory Method S...

The use of MySQL triggers and what to pay attention to

Table of contents About Triggers Use of triggers ...

Should I abandon JQuery?

Table of contents Preface What to use if not jQue...

How to make JavaScript sleep or wait

Table of contents Overview Checking setTimeout() ...

Summary of Vue watch monitoring methods

Table of contents 1. The role of watch in vue is ...

HTML markup language - table tag

Click here to return to the 123WORDPRESS.COM HTML ...

React realizes secondary linkage effect (staircase effect)

This article shares the specific code of React to...

Detailed analysis of Vue child components and parent components

Table of contents 1. Parent components and child ...

Mysql experiment: using explain to analyze the trend of indexes

Overview Indexing is a skill that must be mastere...

Solution to the inaccessibility of Tencent Cloud Server Tomcat port

I recently configured a server using Tencent Clou...

Don’t bother with JavaScript if you can do it with CSS

Preface Any application that can be written in Ja...

Native JavaScript to achieve slide effects

When we create a page, especially a homepage, we ...