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

UDP simple server client code example

I won’t go into details about the theory of UDP. ...

XHTML Getting Started Tutorial: What is XHTML?

What is HTML? To put it simply: HTML is used to m...

How to set a dotted border in html

Use CSS styles and HTML tag elements In order to ...

How to implement Mysql switching data storage directory

How to implement Mysql switching data storage dir...

JavaScript dynamically generates a table with row deletion function

This article example shares the specific code of ...

Small program to implement a simple calculator

This article example shares the specific code of ...

Summary of Common Problems with Mysql Indexes

Q1: What indexes does the database have? What are...

Solution to css3 transform transition jitter problem

transform: scale(); Scaling will cause jitter in ...

Let's talk about destructuring in JS ES6

Overview es6 adds a new way to get specified elem...