{"name":"use-debouncy","version":"4.3.1","author":{"name":"Egor Avakumov"},"description":"🌀 Small (~0.2kb) debounce effect hook for React with TypeScript support","license":"MIT","keywords":["debounce","use-debounce","react debounce","debounce hook","use-debouncy","use-effect","react","react hook","hooks","typescript"],"repository":{"url":"git+https://github.com/eavam/use-debouncy.git","type":"git"},"main":"lib/index.js","typings":"lib/index.d.ts","module":"lib/index.es.js","sideEffects":false,"scripts":{"size":"size-limit","test":"jest","serve:e2e":"npx parcel@1.12.3 cypress/app/index.html","cypress:open":"cypress open","lint":"eslint . --ext .js,.ts","build":"rollup -c","clear":"rimraf lib","prebuild":"npm run clear && tsc -p tsconfig.declaration.json","semantic-release":"semantic-release","prepare":"is-ci || husky install","stryker":"stryker run"},"peerDependencies":{"react":"^16.8.0 || ^17.0.0 || ^18.0.0"},"devDependencies":{"@commitlint/cli":"16.2.3","@commitlint/config-conventional":"16.2.1","@rollup/plugin-commonjs":"21.0.3","@rollup/plugin-sucrase":"4.0.2","@semantic-release/changelog":"6.0.1","@semantic-release/commit-analyzer":"9.0.2","@semantic-release/exec":"6.0.3","@semantic-release/git":"10.0.1","@semantic-release/github":"8.0.4","@semantic-release/npm":"8.0.3","@semantic-release/release-notes-generator":"10.0.3","@size-limit/preset-small-lib":"5.0.5","@size-limit/time":"7.0.8","@testing-library/react-hooks":"7.0.2","@types/react":"17.0.43","@types/react-dom":"17.0.14","@types/jest":"27.4.1","@typescript-eslint/eslint-plugin":"5.17.0","@typescript-eslint/parser":"5.17.0","@stryker-mutator/core":"5.6.1","@stryker-mutator/jest-runner":"5.6.1","@stryker-mutator/typescript-checker":"5.6.1","bit-bin":"14.8.8","cypress":"9.5.3","eslint":"8.12.0","eslint-config-prettier":"8.5.0","eslint-plugin-cypress":"2.12.1","eslint-plugin-import":"2.25.4","eslint-plugin-prettier":"4.0.0","eslint-plugin-react":"7.29.4","eslint-plugin-react-hooks":"4.4.0","eslint-plugin-unicorn":"37.0.1","husky":"7.0.4","is-ci":"3.0.1","prettier":"2.6.1","jest":"27.5.1","jest-environment-jsdom":"27.5.1","pretty-quick":"3.1.3","fast-check":"2.24.0","react":"18.0.0","react-dom":"18.0.0","rimraf":"3.0.2","rollup":"2.70.1","rollup-plugin-terser":"7.0.2","semantic-release":"18.0.1","size-limit":"7.0.8","typescript":"4.6.3","ts-node":"10.7.0","ts-jest":"27.1.4"},"publishConfig":{"access":"public"},"bit":{"env":{"compiler":"bit.envs/compilers/react-typescript@3.1.54"},"componentsDefaultDirectory":"components/{name}","packageManager":"npm"},"gitHead":"31662deb5a92bce8b68248de991208700fa3ac9e","bugs":{"url":"https://github.com/eavam/use-debouncy/issues"},"homepage":"https://github.com/eavam/use-debouncy#readme","_id":"use-debouncy@4.3.1","_nodeVersion":"14.21.1","_npmVersion":"7.24.2","dist":{"integrity":"sha512-K+qtK89KojRB2GbTGtmJRysSii+wVg540bYeW9YBF7jqtwoGjIpY3m71BP0NeZzOMCcbZ6ZodLw6QeN3ascTZg==","shasum":"a0d48ac20300ff96d4fbacc9149d14a82bb68907","tarball":"http://registry-npm.ywwl.com/use-debouncy/download/use-debouncy-4.3.1.tgz","fileCount":20,"unpackedSize":31429,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDHjzLCUlIJ4yMDfQR4nnjoAfHIAYXFCmJowCuVzQt7ogIhAKp02B6j3p4s+Z7TMSf5WnnGnwJ3lQpP+cr7I6pHV4Pw"}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjkoHuACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmpalg//RLS3fJnJZ8I35AVeXItqd/28bTTuM6bVRFZky/UE0AZ9UcVk\r\n9c2Mg8+2Ojq0e9hBAApAmxEngjiSyC+JWDAy0PFcd3kdUEZMwqP5rs5dC6wY\r\n9bGWOfgbAeoDI61BP8HAnR/RCnCden4tvCqXvAxhRG3Zz3PgIz6pa/WZ14gh\r\nFxjGdk6BGoXqQn7enbkVA0DhpKwVUx4nOZUrP78PiwbjsQzV8Gb7v8gJ/G1x\r\nBId3wzVwKbSMsr5/pqjK/mx6Q80T+WX34uZefeTpufmAqc9LiY/ImJy23GVK\r\n8bPZMU8jjE+zBEtu/KDy0vN2y/9gfoMy9ngPu5Oc6FjMk8PH14IvqEhX4hjx\r\nysJHfpNmx8u7DqxRzJg9JnF9vLq1lDVM4W1C48Uc4qOmL3jMQomXAekhd8ly\r\nlqIIMsJOwWTKYrNf67BPm5IWNpKIfNKg3nBb/QN0ZECBiLN84RzjUPN7oCdH\r\nfz0TUHFS9iiuWol0Ncf3FTRM5td9sHG2XyOAKUlQvpPKIlcJe7MIpOsoSE8B\r\n/8oOP5H8r9cnpbz3tp2kSTIZHnsINqhdGVSIgU1Dq11IvmgulMa+/IQLeKEp\r\n69BZW0u6c7bfMJKVGakSGNPEzLsiTXdmznPCjsKB1KQBESBx6rJDs4GgOG2S\r\nljZM5M5c+IVseZoV2ALX97l1KsYLdRJgxMA=\r\n=t8+C\r\n-----END PGP SIGNATURE-----\r\n","size":11957,"noattachment":false,"key":"/use-debouncy/-/use-debouncy-4.3.1.tgz"},"_npmUser":{"name":"eavam","email":"avakymov21@gmail.com"},"directories":{},"maintainers":[{"name":"eavam","email":"avakymov21@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/use-debouncy_4.3.1_1670545902726_0.13647477024553467"},"_hasShrinkwrap":false,"readme":"# useDebouncy\n\n🌀 Small (~0.2kb) debounce effect hook for React with TypeScript support\n\n![GitHub](https://img.shields.io/github/license/eavam/use-debouncy)\n![npm bundle size](https://img.shields.io/bundlephobia/minzip/use-debouncy)\n![npm](https://img.shields.io/npm/dm/use-debouncy)\n![types](https://badgen.net/npm/types/use-debouncy)\n[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Feavam%2Fuse-debouncy.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Feavam%2Fuse-debouncy?ref=badge_shield)\n\n![](assets/example.gif)\n\n## Features\n\n- 👌 **No dependencies.**\n- 🏋️‍ **Tiny.** ~0.2kb.\n- 🦾 **Frame-aligned.** Driven by `requestAnimationFrame`.\n- 📖 **Types.** Written in TypeScript, ships its own declarations.\n- 🎣 **Three hooks.** Debounce an effect, a callback or a value.\n\n## Installation\n\n```sh\nnpm install use-debouncy\n```\n\n```sh\nyarn add use-debouncy\n```\n\n```sh\npnpm add use-debouncy\n```\n\nRequires React 18 or 19 as a peer dependency.\n\n## Usage\n\nThree hooks, one idea: do the work only after things have stopped changing for a\nwhile. Pick the one that fits what you already have.\n\n### Debounce an effect\n\nReads like `useEffect`, but waits for the dependencies to settle. It does not\nrun on the initial render.\n\n```tsx\nimport { useState } from 'react';\nimport { useDebouncyEffect } from 'use-debouncy';\n\nconst Search = () => {\n  const [value, setValue] = useState('');\n\n  useDebouncyEffect(\n    () => fetchData(value), // called once typing stops\n    400, // milliseconds to wait\n    [value], // dependencies, like useEffect\n  );\n\n  return (\n    <input value={value} onChange={(event) => setValue(event.target.value)} />\n  );\n};\n```\n\nLike `useEffect`, the callback may return a destructor. It runs before the next\ninvocation and when the component unmounts:\n\n```tsx\nuseDebouncyEffect(\n  () => {\n    const controller = new AbortController();\n    fetchData(value, { signal: controller.signal });\n\n    return () => controller.abort();\n  },\n  400,\n  [value],\n);\n```\n\n### Debounce a callback\n\nReturns a function that delays the call until it stops being called. Handy for\nevent handlers, where there is no dependency array to speak of.\n\n```tsx\nimport type { ChangeEvent } from 'react';\nimport { useDebouncyFn } from 'use-debouncy';\n\nconst Search = () => {\n  const handleChange = useDebouncyFn(\n    (event: ChangeEvent<HTMLInputElement>) => fetchData(event.target.value),\n    400,\n  );\n\n  return <input onChange={handleChange} />;\n};\n```\n\nThe returned function keeps the same identity across renders, so it is safe to\nhand to a memoized child or to put in a dependency array. It also carries two\ncontrols for the call that is currently waiting:\n\n```tsx\nconst save = useDebouncyFn(saveDraft, 1000);\n\nsave.flush(); // run the pending call now\nsave.cancel(); // drop it instead\n```\n\n### Debounce a value\n\nThe shortest path when the value already lives in state — you get a copy that\ntrails behind until things go quiet.\n\n```tsx\nimport { useEffect, useState } from 'react';\nimport { useDebouncyValue } from 'use-debouncy';\n\nconst Search = () => {\n  const [value, setValue] = useState('');\n  const query = useDebouncyValue(value, 400);\n\n  useEffect(() => {\n    fetchData(query);\n  }, [query]);\n\n  return (\n    <input value={value} onChange={(event) => setValue(event.target.value)} />\n  );\n};\n```\n\n## Recipes\n\n### Autosave that survives navigation\n\nDebounce the writes while typing, and flush the last one when the user leaves.\n\n```tsx\nconst Editor = ({ id }: { id: string }) => {\n  const [draft, setDraft] = useState('');\n  const save = useDebouncyFn((text: string) => saveDraft(id, text), 1000);\n\n  // Nothing is lost on unmount: the pending write goes out immediately\n  useEffect(() => () => save.flush(), [save]);\n\n  return (\n    <textarea\n      value={draft}\n      onChange={(event) => {\n        setDraft(event.target.value);\n        save(event.target.value);\n      }}\n    />\n  );\n};\n```\n\n### Validation that stops when the field is cleared\n\n```tsx\nconst Email = () => {\n  const [email, setEmail] = useState('');\n  const [error, setError] = useState<string | null>(null);\n\n  const validate = useDebouncyFn((value: string) => {\n    setError(isEmail(value) ? null : 'Enter a valid email');\n  }, 500);\n\n  return (\n    <input\n      value={email}\n      onChange={(event) => {\n        const { value } = event.target;\n        setEmail(value);\n        setError(null);\n\n        // No point validating an empty field, so drop the pending run\n        if (value) validate(value);\n        else validate.cancel();\n      }}\n    />\n  );\n};\n```\n\n## API\n\n### `useDebouncyEffect(fn, wait?, deps?)`\n\n```ts\nfunction useDebouncyEffect(\n  fn: EffectCallback,\n  wait?: number,\n  deps?: DependencyList,\n): void;\n```\n\n| Argument | Required | Default | Description                                                   |\n| -------- | -------- | ------- | ------------------------------------------------------------- |\n| `fn`     | ✓        |         | Called once the dependencies settle. May return a destructor. |\n| `wait`   |          | `0`     | Milliseconds to wait.                                         |\n| `deps`   |          | `[]`    | Dependencies, as in `useEffect`.                              |\n\nSkips the initial render, restarts the timer whenever the dependencies change,\nand cancels a pending call on unmount.\n\n### `useDebouncyFn(fn, wait?)`\n\n```ts\nfunction useDebouncyFn<Args extends unknown[]>(\n  fn: (...args: Args) => unknown,\n  wait?: number,\n): DebouncyFn<Args>;\n```\n\n| Argument | Required | Default | Description                                       |\n| -------- | -------- | ------- | ------------------------------------------------- |\n| `fn`     | ✓        |         | Called with the arguments of the last invocation. |\n| `wait`   |          | `0`     | Milliseconds to wait.                             |\n\nReturns a function with a stable identity, which also exposes:\n\n| Method     | Description                                |\n| ---------- | ------------------------------------------ |\n| `cancel()` | Drops the pending call, if any.            |\n| `flush()`  | Runs the pending call immediately, if any. |\n\n### `useDebouncyValue(value, wait?)`\n\n```ts\nfunction useDebouncyValue<Value>(value: Value, wait?: number): Value;\n```\n\n| Argument | Required | Default | Description           |\n| -------- | -------- | ------- | --------------------- |\n| `value`  | ✓        |         | Value to trail.       |\n| `wait`   |          | `0`     | Milliseconds to wait. |\n\nReturns the value unchanged on the first render, then updates once it has\nstopped changing.\n\n### Types\n\n```ts\nimport type { DebouncyFn } from 'use-debouncy';\n\ntype DebouncyFn<Args extends unknown[]> = ((...args: Args) => void) & {\n  cancel: () => void;\n  flush: () => void;\n};\n```\n\n## Good to know\n\n**The timer follows frames, not the wall clock.** Waiting is driven by\n`requestAnimationFrame`, so the callback lands right before a repaint, together\nwith the rest of the frame's work. The flip side: browsers pause frames for\nhidden tabs, so a pending call resumes only when the tab becomes visible again.\nWork that has to happen while the user is away belongs in `visibilitychange` or\n`sendBeacon` instead.\n\n**Server rendering works.** Nothing touches browser globals during render, so\n`renderToString` is fine — the timer only ever starts in the browser.\n\n**You may not need this package.** If the only goal is to keep a heavy render\nfrom blocking typing, React's own `useDeferredValue` does that with no\ndependency at all. Reach for these hooks when you want to delay a _side effect_:\na request, an autosave, a validation.\n\n**Testing.** Fake timers have to mock `requestAnimationFrame` as well, or the\ncallback never fires. `jest.useFakeTimers()` and Playwright's\n`page.clock.install()` both do.\n\n## Development\n\n```bash\nyarn install\nyarn hooks      # once per clone: installs the pre-commit hook\n\nyarn dev        # story gallery at http://localhost:3100/playwright/gallery/index.html\nyarn test       # component tests in Chromium, Firefox and WebKit\nyarn test --ui  # same, in Playwright's UI mode\nyarn lint       # oxlint + oxfmt\nyarn typecheck  # tsc\nyarn build      # bundle into lib/\n```\n\nComponents under test live in `playwright/stories/*.story.tsx`, one export per\nscenario, and the tests address them by id. The gallery is served by the\nproject's own Vite dev server and renders stories in `StrictMode`, so React's\ndevelopment-only behaviour is covered too. Open the gallery URL in a browser to\neyeball every story by hand.\n\nCommit messages follow [Conventional Commits](https://www.conventionalcommits.org)\n— they decide the released version.\n\n## License\n\nMIT © [Egor Avakumov](https://github.com/eavam)\n\n[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Feavam%2Fuse-debouncy.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Feavam%2Fuse-debouncy?ref=badge_large)\n","publish_time":1670545902937,"_cnpm_publish_time":1670545902937,"dist-tags":{"beta":"5.0.1-beta.3","latest":"6.0.0"}}