1. What are custom hooks
Logical reuse
Simply put, using a custom hook can extract certain component logic into reusable functions. Custom hook is auseStart calling other hooks Javascript functions.
2. When not using a custom hook
Example 1:When our entire page needs to get the coordinates of the user's mouse movement, we do not use hook code, we can write this way
const [position, setPosition] = useState({ x: 0, y: 0 }) useEffect(() => { const move = (e) => { setPosition({ x: , y: }) } ('mousemove', move) return () => { ('mousemove', move) } }, []) return ( <div> x:{} y:{} </div> )
Example 2: When there is an image on our page that you want to move with the mouse, we can also write it like this without using hook code:
const [position, setPosition] = useState({ x: 0, y: 0 }) useEffect(() => { const move = (e) => { setPosition({ x: , y: }) } ('mousemove', move) return () => { ('mousemove', move) } }, []) return ( <div> <img src={img} style={{ position: 'absolute', top: , left: , }} alt="" /> </div> )
It is obvious that the above two examples have different effects, but when most of the logical codes used are the same, we can use hooks to logically reuse these logical codes.
3. Use custom hooks
We extract the logical code that can be reused 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: , y: }) } ('mousemove', move) return () => { ('mousemove', move) } }, []) return position }
We extracted this function in the useMousePosition function. Now we can import it anywhere we want to use!
Finally, use it like using a normal function.
const position = useMousePosition() return ( <div> x:{} y:{} </div> )
It's obvious that the code volume has been reduced
This is the end of this article about creating custom hooks in react. For more related react custom hooks content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!