auto
Navigate back to the homepage

React Hooks

Ricky Marcon
August 3rd, 2019 · 1 min read

React hooks let you use state and other React features without writing a class.

Why hooks?

  1. It’s hard to reuse stateful logic between components;
  2. Complex components become hard to understand; and
  3. 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';
2
3function useHover(props) {
4 const ref = useRef(null);
5
6 const [value, setValue] = useState(false);
7
8 const handleMouseOver = () => setValue(true);
9 const handleMouseLeave = () => setValue(false);
10
11 useEffect(() => {
12 const node = ref.current;
13
14 if (node) {
15 node.addEventListener('mouseover', handleMouseOver);
16 node.addEventListener('mouseleave', handleMouseLeave);
17
18 return () => {
19 node.removeEventListener('mouseover', handleMouseOver);
20 node.removeEventListener('mouseleave', handleMouseLeave);
21 };
22 }
23 }, []);
24
25 return [ref, value];
26}
27
28export default useHover;

More articles from Ricky Marcon

How to run a GraphQL Server using Firebase Cloud Functions

Easily create a serverless, auto-scaling GraphQL API using Firebase Cloud Functions.

October 21st, 2019 · 2 min read

React Hooks

A collection of useful React hooks.

August 3rd, 2019 · 1 min read
© 2019 Ricky Marcon
Link to $https://stackoverflow.com/users/3998659/rickyLink to $https://twitter.com/ricky_marconLink to $https://www.linkedin.com/in/rickymarcon