Skip to content

Commit d4b9c2d

Browse files
committed
Added useMouseCoords hook
1 parent 7516717 commit d4b9c2d

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/App.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
import React from "react";
2+
import useMouseCoords from "./hooks/useMouseCoords";
23
import "./styles.css";
34

45
export default function App() {
6+
const [x,y] = useMouseCoords();
57
return (
68
<div className="App">
79
<h1>Custom Hook Series</h1>
810
<h2>Let's create some useful hooks in React.JS!</h2>
911
<div className="container">
10-
<span>X</span>
12+
<span>{x}</span>
1113
<span> - </span>
12-
<span>Y</span>
14+
<span>{y}</span>
1315
</div>
1416
</div>
1517
);

src/hooks/useMouseCoords.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { useState, useEffect } from "react";
2+
3+
const useMouseCoords = () => {
4+
5+
const [coords, setCoords] = useState([0,0]);
6+
7+
useEffect(() => {
8+
const handleCoords = ({ clientX, clientY }) => {
9+
setCoords([clientX, clientY]);
10+
}
11+
12+
window.addEventListener("mousemove", handleCoords);
13+
14+
return () => {
15+
window.removeEventListener("mousemove", handleCoords);
16+
}
17+
18+
}, []);
19+
20+
return coords;
21+
}
22+
23+
export default useMouseCoords;

0 commit comments

Comments
 (0)