React - implementing a hook for a search input - different ways of adding event listener

123 Views Asked by At

Just came up with this idea of custom useSearchINput hook as there is no support in React for a 'X' clearing button for input["search"] `

import { useEffect, useRef, useState } from "react";

export default function useSearchInput(initValue) {

    const [value, setValue] = useState(initValue)
    const ref = useRef()

    function onChange(e) {
        setValue(e.target.value)
    }

    useEffect(() => {
        if (ref.current?.type === "search") {
            ref.current.defaultValue = initValue || ''
            ref.current.onkeyup = onChange
            ref.current.addEventListener("search", onChange)
        }

        return () => {
            ref.current.removeEventListener("search", onChange) 
        }
    })

    return [ref, value]
}

`

The above works but could be implemented better? Any ideas?

Also, I noticed there are two ways of adding onChange callback:

  1. ref.current.onkeyup = onChange

  2. ref.current.addEventListener("keyup", onChange)

Is there any difference in any aspects between them? (besides fact that for option 2 we need to remove listener in returned function from useEffect). Examples on the web show the latter one as a correct way but first one seems like much less typing.

0

There are 0 best solutions below