React hooks let you use state and other React features without writing a class.
Why hooks?
- It’s hard to reuse stateful logic between components;
- Complex components become hard to understand; and
- Classes confuse both people and machines.
Useful hooks
useHover
Detecting when a user is hovering over an element is a common problem most web developers face when building applications. I found this hook to be a nice way of reusing this logic across my applications.
1import { useRef, useEffect, useState } from 'react';23function useHover(props) {4 const ref = useRef(null);56 const [value, setValue] = useState(false);78 const handleMouseOver = () => setValue(true);9 const handleMouseLeave = () => setValue(false);1011 useEffect(() => {12 const node = ref.current;1314 if (node) {15 node.addEventListener('mouseover', handleMouseOver);16 node.addEventListener('mouseleave', handleMouseLeave);1718 return () => {19 node.removeEventListener('mouseover', handleMouseOver);20 node.removeEventListener('mouseleave', handleMouseLeave);21 };22 }23 }, []);2425 return [ref, value];26}2728export default useHover;