Teach you to create custom hooks in react

  • 2021-12-05 05:29:52
  • OfStack

1. What is a custom hooks

Logical multiplexing

Simply put, some component logic can be extracted into reusable functions using custom hook. Custom hook is an Javascript function that starts with use and calls other hook.

2. When not using custom hook

Example 1: When we need to get the coordinates of the user's mouse movement on the whole page, we can write this instead of using hook code


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

Example 2: When we have a picture in our page to follow the mouse, instead of using the code of hook, we can also write this:


const [position, setPosition] = useState({
    x: 0,
    y: 0
  })
  useEffect(() => {
    const move = (e) => {
      setPosition({ x: e.x, y: e.y })
    }
    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 rendering effects, but when most of the logic codes used are the same, we can use hook for logical reuse

3. Use custom hook

We extract the reusable logic code in the above two examples and create a new file named useMousePosition


import { useState, useEffect } from 'react'
export default function useMousePosition() {
  const [position, setPosition] = useState({
    x: 0,
    y: 0
  })
  useEffect(() => {
    const move = (e) => {
      setPosition({ x: e.x, y: e.y })
    }
    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, just use it like a normal function


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

It obviously reduces the amount of code


Related articles: