useClickOutside
Hooks used in this custom hook: useEffect
In Chapter 8, Use Ref to Hide Stuff, we learned about a case where we can detect when a user clicks outside a component. This feature is pretty generic and we want to take advantage of this in various parts of the project, such as dismissing a modal or tooltip – see Figure 9.5.
Let's see if we can refactor the old code a bit and turn it into a custom useClickOutside
hook:
function useClickOutside(ref, handler) { useEffect(() => { const evt = e => { if (!ref.current) return if (!ref.current.contains(e.target)) { handler && handler() } } window.addEventListener("mousedown"...