Skip to content

Commit

Permalink
feat: add useMousePosition #21
Browse files Browse the repository at this point in the history
  • Loading branch information
dlcastillop committed Dec 24, 2024
1 parent 0958bdd commit 1547a86
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
32 changes: 32 additions & 0 deletions snippets/js.code-snippets
Original file line number Diff line number Diff line change
Expand Up @@ -926,6 +926,38 @@
],
"description": "React hook to store, retrieve and delete data from the browser's localStorage API"
},
"useMousePosition": {
"prefix": "useMousePosition",
"body": [
"import { useSyncExternalStore } from 'react';",
"",
"let mousePosition = { x: 0, y: 0 };",
"",
"export const useMousePosition = () => {",
" const subscribe = (callback) => {",
" const handleMouseMove = (event) => {",
" mousePosition = {",
" x: event.clientX,",
" y: event.clientY",
" };",
" callback();",
" };",
"",
" window.addEventListener('mousemove', handleMouseMove);",
" return () => {",
" window.removeEventListener('mousemove', handleMouseMove);",
" };",
" };",
"",
" const getSnapshot = () => mousePosition;",
"",
" const getServerSnapshot = () => ({ x: 0, y: 0 });",
"",
" return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);",
"};"
],
"description": "React hook to track the current position of the mouse on the screen"
},
"useNavigatorShare": {
"prefix": "useNavigatorShare",
"body": [
Expand Down
37 changes: 37 additions & 0 deletions snippets/ts.code-snippets
Original file line number Diff line number Diff line change
Expand Up @@ -1001,6 +1001,43 @@
],
"description": "React hook to store, retrieve and delete data from the browser's localStorage API"
},
"useMousePosition": {
"prefix": "useMousePosition",
"body": [
"import { useSyncExternalStore } from 'react';",
"",
"interface MousePosition {",
" x: number;",
" y: number;",
"}",
"",
"let mousePosition: MousePosition = { x: 0, y: 0 };",
"",
"export const useMousePosition = (): MousePosition => {",
" const subscribe = (callback: () => void) => {",
" const handleMouseMove = (event: MouseEvent) => {",
" mousePosition = {",
" x: event.clientX,",
" y: event.clientY",
" };",
" callback();",
" };",
"",
" window.addEventListener('mousemove', handleMouseMove);",
" return () => {",
" window.removeEventListener('mousemove', handleMouseMove);",
" };",
" };",
"",
" const getSnapshot = (): MousePosition => mousePosition;",
"",
" const getServerSnapshot = (): MousePosition => ({ x: 0, y: 0 });",
"",
" return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);",
"};"
],
"description": "React hook to track the current position of the mouse on the screen"
},
"useNavigatorShare": {
"prefix": "useNavigatorShare",
"body": [
Expand Down

0 comments on commit 1547a86

Please sign in to comment.