Skip to content

Commit

Permalink
chore: add debounce for translate word (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
ratmirslv committed Jan 26, 2024
1 parent 8c79c0d commit 7c46619
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 3 additions & 1 deletion components/Word.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useDisclosure } from '@mantine/hooks'

import TranslateWordPopup from './TranslateWordPopup'

import useDebounce from '@/hooks/useDebounce'
import { clearWord } from 'utils/clearWord'

interface WordProps {
Expand All @@ -12,11 +13,12 @@ interface WordProps {
function Word(props: WordProps) {
const [opened, { close, open }] = useDisclosure(false)

const debouncedOpen = useDebounce(opened, 400)
return (
<Popover
width={200}
position="top-start"
opened={opened}
opened={opened ? debouncedOpen : false}
offset={{ mainAxis: 0, crossAxis: 5 }}
>
<Popover.Target>
Expand Down
12 changes: 12 additions & 0 deletions hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { useState, useEffect } from 'react'

export default function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState(value)

useEffect(() => {
const handler = setTimeout(() => setDebouncedValue(value), delay)
return () => clearTimeout(handler)
}, [delay, value])

return debouncedValue
}

0 comments on commit 7c46619

Please sign in to comment.