Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/deep-pandas-stare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'react-simplikit': major
---

Time-related options and parameters now include `Ms` in their names.
These option keys are renamed, so existing calls need to be updated:

- `useDebouncedCallback`: `timeThreshold` → `debounceMs`
- `useThrottledCallback`: `timeThreshold` → `throttleMs`
- `useImpressionRef`, `ImpressionArea`: `timeThreshold` → `timeThresholdMs`
- `useLongPress`: `delay` → `delayMs`
- `useAvoidKeyboard`: `transitionDuration` → `transitionDurationMs`

```ts
// before
useDebouncedCallback({ onChange: setQuery, timeThreshold: 300 });
// after
useDebouncedCallback({ onChange: setQuery, debounceMs: 300 });
```

The positional `wait` parameter of `useDebounce`, `useDebouncedValue`, `useThrottle` and `useThrottledValue` is now `debounceMs` / `throttleMs`. Calls like `useDebounce(fn, 300)` keep working.
2 changes: 1 addition & 1 deletion docs/es/use-cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ Usa [useDebouncedValue](/es/hooks/useDebouncedValue) cuando necesites un valor p

- `useStorageState` usa `defaultValue` para la instantánea del servidor y la hidratación, y luego lee el almacenamiento del navegador en el cliente. Al desmontarse, elimina los listeners de almacenamiento.

- `useDebounce` cancela las llamadas pendientes cuando el componente se desmonta o cambian `wait`, `leading` o `trailing`. No cancela una solicitud de red que ya haya comenzado; tu aplicación debe gestionar la cancelación o las respuestas obsoletas.
- `useDebounce` cancela las llamadas pendientes cuando el componente se desmonta o cambian `debounceMs`, `leading` o `trailing`. No cancela una solicitud de red que ya haya comenzado; tu aplicación debe gestionar la cancelación o las respuestas obsoletas.

- Las mediciones del navegador pueden cambiar después del montaje. Consulta los valores iniciales y las restricciones de plataforma en [Web móvil](/es/mobile-web) y en la referencia de cada API.

Expand Down
2 changes: 1 addition & 1 deletion docs/ja/use-cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export function FruitSearch() {

- `useStorageState` はサーバースナップショットと hydration に `defaultValue` を使い、その後クライアントでブラウザストレージを読み取ります。アンマウント時にストレージのリスナーを解除します。

- `useDebounce` はコンポーネントのアンマウント時、または `wait`、`leading`、`trailing` の変更時に保留中の呼び出しをキャンセルします。開始済みのネットワークリクエストはキャンセルしないため、リクエストの中止や古いレスポンスの処理はアプリケーション側で行う必要があります。
- `useDebounce` はコンポーネントのアンマウント時、または `debounceMs`、`leading`、`trailing` の変更時に保留中の呼び出しをキャンセルします。開始済みのネットワークリクエストはキャンセルしないため、リクエストの中止や古いレスポンスの処理はアプリケーション側で行う必要があります。

- ブラウザの測定値はマウント後に変わることがあります。初期値とプラットフォームの制約は [モバイル Web](/ja/mobile-web) と各 API のリファレンスで確認してください。

Expand Down
2 changes: 1 addition & 1 deletion docs/ko/use-cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export function FruitSearch() {

- `useStorageState`는 서버 스냅샷과 hydration에 `defaultValue`를 사용한 뒤 클라이언트에서 브라우저 저장소를 읽어요. 언마운트 시 저장소 리스너를 제거해요.

- `useDebounce`는 컴포넌트가 언마운트되거나 `wait`, `leading`, `trailing`이 바뀌면 대기 중인 호출을 취소해요. 이미 시작한 네트워크 요청은 취소하지 않으므로 요청 취소나 오래된 응답 처리는 애플리케이션에서 담당해야 해요.
- `useDebounce`는 컴포넌트가 언마운트되거나 `debounceMs`, `leading`, `trailing`이 바뀌면 대기 중인 호출을 취소해요. 이미 시작한 네트워크 요청은 취소하지 않으므로 요청 취소나 오래된 응답 처리는 애플리케이션에서 담당해야 해요.

- 브라우저 측정값은 마운트 후에 바뀔 수 있어요. 초기값과 플랫폼 제약은 [모바일 웹](/ko/mobile-web) 가이드와 개별 API 레퍼런스에서 확인하세요.

Expand Down
2 changes: 1 addition & 1 deletion docs/use-cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ Use [useDebouncedValue](/hooks/useDebouncedValue) when you need a value for rend

- `useStorageState` uses `defaultValue` for the server snapshot and hydration, then reads browser storage on the client. Its storage listeners are removed on unmount.

- `useDebounce` cancels pending calls when the component unmounts or when `wait`, `leading`, or `trailing` changes. It does not cancel a network request that has already started; the application must handle request cancellation or stale responses.
- `useDebounce` cancels pending calls when the component unmounts or when `debounceMs`, `leading`, or `trailing` changes. It does not cancel a network request that has already started; the application must handle request cancellation or stale responses.

- Browser measurements can change after mount. Check the initial values and platform constraints in [Mobile Web](/mobile-web) and the individual API reference.

Expand Down
2 changes: 1 addition & 1 deletion docs/zh-Hans/use-cases.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export function FruitSearch() {

- `useStorageState` 使用 `defaultValue` 作为服务端快照和 hydration 的值,随后在客户端读取浏览器存储。卸载时会移除存储监听器。

- `useDebounce` 在组件卸载或 `wait`、`leading`、`trailing` 发生变化时取消待执行的调用,但不会取消已经开始的网络请求。应用需要处理请求取消或过期响应。
- `useDebounce` 在组件卸载或 `debounceMs`、`leading`、`trailing` 发生变化时取消待执行的调用,但不会取消已经开始的网络请求。应用需要处理请求取消或过期响应。

- 浏览器测量值可能在挂载后发生变化。请在[移动 Web](/zh-Hans/mobile-web) 指南和各 API 参考文档中查看初始值及平台限制。

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ function ImpressionArea<T extends ElementType>(
as: T = 'div',
rootMargin?: string,
areaThreshold?: number,
timeThreshold?: number,
timeThresholdMs?: number,
onImpressionStart?: () => void,
onImpressionEnd?: () => void,
ref?: Ref<Element<T>>,
Expand Down Expand Up @@ -41,7 +41,7 @@ function ImpressionArea<T extends ElementType>(
/>

<Interface
name="timeThreshold"
name="timeThresholdMs"
type="number"
description="Minimum time the element must be visible (in milliseconds)."
/>
Expand Down Expand Up @@ -92,7 +92,7 @@ function App() {
<ImpressionArea
onImpressionStart={() => console.log('Element entered view')}
onImpressionEnd={() => console.log('Element exited view')}
timeThreshold={1000}
timeThresholdMs={1000}
areaThreshold={0.5}
>
<div>Track me!</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ function useAvoidKeyboard(
'Base bottom offset in pixels when the keyboard is hidden. Useful for accounting for the iPhone home indicator area.',
},
{
name: 'options.transitionDuration',
name: 'options.transitionDurationMs',
type: 'number',
required: false,
defaultValue: '200',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
`useDebounce` is a React hook that returns a debounced version of the provided callback function.
It helps optimize event handling by delaying function execution and grouping multiple calls into one.

With the default options, the last call runs after `wait` milliseconds without another call.
Pending calls are cancelled when the component unmounts or when `wait`, `leading`, or `trailing` changes.
With the default options, the last call runs after `debounceMs` milliseconds without another call.
Pending calls are cancelled when the component unmounts or when `debounceMs`, `leading`, or `trailing` changes.
Calling `.cancel()` only cancels a pending callback, not an already-started network request.
The example displays the query locally. To search a server, pass your application's
search callback as the first argument to `useDebounce`.
Expand All @@ -14,7 +14,7 @@ search callback as the first argument to `useDebounce`.
```ts
function useDebounce<F extends (...args: any[]) => unknown>(
callback: F,
wait: number,
debounceMs: number,
options?: DebounceOptions
): F & { cancel: () => void };
```
Expand All @@ -30,7 +30,7 @@ function useDebounce<F extends (...args: any[]) => unknown>(

<Interface
required
name="wait"
name="debounceMs"
type="number"
description="The number of milliseconds to delay the function execution."
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function useDebouncedCallback<T>(options: Object): (nextValue: T) => void;
'The callback to debounce. A call with the same value as the last forwarded one is skipped.',
},
{
name: 'options.timeThreshold',
name: 'options.debounceMs',
type: 'number',
required: true,
description:
Expand Down Expand Up @@ -70,7 +70,7 @@ function SearchInput() {
const [query, setQuery] = useState('');
const setQueryDebounced = useDebouncedCallback({
onChange: setQuery,
timeThreshold: 300,
debounceMs: 300,
});

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

`useDebouncedValue` is a React hook that returns a debounced copy of the given value.
The caller keeps owning the state; the hook only delays how quickly the returned value follows it.
The returned value updates `wait` milliseconds after the last change, which is useful for
The returned value updates `debounceMs` milliseconds after the last change, which is useful for
deriving a search query or a validation input from fast-changing state.

Pending updates are cancelled when the component unmounts. The example displays the
Expand All @@ -13,15 +13,15 @@ on mount, so with `leading: true` the first change after mount is applied immedi
If both `leading` and `trailing` are `false`, the returned value never updates.

The value is compared by reference. Passing a new object or array on every render keeps
the returned value updating every `wait` milliseconds; stabilize the reference first, for
the returned value updating every `debounceMs` milliseconds; stabilize the reference first, for
example with `usePreservedReference`.

## Interface

```ts
function useDebouncedValue<T>(
value: T,
wait: number,
debounceMs: number,
options?: DebounceOptions
): T;
```
Expand All @@ -37,7 +37,7 @@ function useDebouncedValue<T>(

<Interface
required
name="wait"
name="debounceMs"
type="number"
description="The number of milliseconds to wait after the last change before updating."
/>
Expand All @@ -61,7 +61,7 @@ function useDebouncedValue<T>(
required: false,
defaultValue: 'true',
description:
'If <code>true</code>, the last change is applied after <code>wait</code> milliseconds.',
'If <code>true</code>, the last change is applied after <code>debounceMs</code> milliseconds.',
},
]"
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function useImpressionRef<Element extends HTMLElement>(
description: 'Callback function executed when the element exits the view',
},
{
name: 'options.timeThreshold',
name: 'options.timeThresholdMs',
type: 'number',
required: false,
defaultValue: '0',
Expand Down Expand Up @@ -72,7 +72,7 @@ function Component() {
const ref = useImpressionRef<HTMLDivElement>({
onImpressionStart: () => console.log('Element entered view'),
onImpressionEnd: () => console.log('Element exited view'),
timeThreshold: 1000,
timeThresholdMs: 1000,
areaThreshold: 0.5,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function useLongPress<E extends HTMLElement>(
description="Configuration options for the long press behavior."
:nested="[
{
name: 'options.delay',
name: 'options.delayMs',
type: 'number',
required: false,
defaultValue: '500',
Expand Down Expand Up @@ -131,7 +131,7 @@ function ContextMenu() {
const [menuVisible, setMenuVisible] = useState(false);

const longPressHandlers = useLongPress(() => setMenuVisible(true), {
delay: 400,
delayMs: 400,
onClick: () => console.log('Normal click'),
onLongPressEnd: () => console.log('Long press completed'),
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ such as when handling scroll or resize events.
```ts
function useThrottle<F extends (...args: any[]) => any>(
callback: F,
wait: number,
throttleMs: number,
options?: ThrottleOptions
): F & { cancel: () => void };
```
Expand All @@ -25,7 +25,7 @@ function useThrottle<F extends (...args: any[]) => any>(

<Interface
required
name="wait"
name="throttleMs"
type="number"
description="The number of milliseconds to throttle invocations to."
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function useThrottledCallback<T>(options: Object): (nextValue: T) => void;
'The callback to throttle. A call with the same value as the last forwarded one is skipped.',
},
{
name: 'options.timeThreshold',
name: 'options.throttleMs',
type: 'number',
required: true,
description: 'The number of milliseconds to throttle invocations to.',
Expand Down Expand Up @@ -67,7 +67,7 @@ function ScrollPosition() {
const [scrollTop, setScrollTop] = useState(0);
const setScrollTopThrottled = useThrottledCallback({
onChange: setScrollTop,
timeThreshold: 200,
throttleMs: 200,
});

return (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# useThrottledValue

`useThrottledValue` is a React hook that returns a throttled copy of the given value.
The caller keeps owning the state; the returned value follows it at most once per `wait` milliseconds,
The caller keeps owning the state; the returned value follows it at most once per `throttleMs` milliseconds,
which is useful for driving expensive renders from scroll position, pointer position, or an element's
size on resize.

Expand All @@ -10,15 +10,15 @@ on mount, so the first change after mount is applied immediately when `leading`
If both `leading` and `trailing` are `false`, the returned value never updates.

The value is compared by reference. Passing a new object or array on every render keeps
the returned value updating every `wait` milliseconds; stabilize the reference first, for
the returned value updating every `throttleMs` milliseconds; stabilize the reference first, for
example with `usePreservedReference`.

## Interface

```ts
function useThrottledValue<T>(
value: T,
wait: number,
throttleMs: number,
options?: ThrottleOptions
): T;
```
Expand All @@ -34,7 +34,7 @@ function useThrottledValue<T>(

<Interface
required
name="wait"
name="throttleMs"
type="number"
description="The length of the throttle window in milliseconds."
/>
Expand All @@ -58,7 +58,7 @@ function useThrottledValue<T>(
required: false,
defaultValue: 'true',
description:
'If <code>true</code>, the last change in a window is applied <code>wait</code> milliseconds after that change.',
'If <code>true</code>, the last change in a window is applied <code>throttleMs</code> milliseconds after that change.',
},
]"
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ function ImpressionArea<T extends ElementType>(
as: T = 'div',
rootMargin?: string,
areaThreshold?: number,
timeThreshold?: number,
timeThresholdMs?: number,
onImpressionStart?: () => void,
onImpressionEnd?: () => void,
ref?: Ref<Element<T>>,
Expand Down Expand Up @@ -41,7 +41,7 @@ function ImpressionArea<T extends ElementType>(
/>

<Interface
name="timeThreshold"
name="timeThresholdMs"
type="number"
description="Minimum time the element must be visible (in milliseconds)."
/>
Expand Down Expand Up @@ -92,7 +92,7 @@ function App() {
<ImpressionArea
onImpressionStart={() => console.log('Element entered view')}
onImpressionEnd={() => console.log('Element exited view')}
timeThreshold={1000}
timeThresholdMs={1000}
areaThreshold={0.5}
>
<div>Track me!</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type Props<Tag extends ElementType> = React.ComponentPropsWithoutRef<Tag> &
* @param {T} [as='div'] - The HTML tag to render. Defaults to `div`.
* @param {string} [rootMargin] - Margin to adjust the detection area.
* @param {number} [areaThreshold] - Minimum ratio of the element that must be visible (0 to 1).
* @param {number} [timeThreshold] - Minimum time the element must be visible (in milliseconds).
* @param {number} [timeThresholdMs] - Minimum time the element must be visible (in milliseconds).
* @param {() => void} [onImpressionStart] - Callback function executed when the element enters the view.
* @param {() => void} [onImpressionEnd] - Callback function executed when the element exits the view.
* @param {Ref<Element<T>>} [ref] - Reference to the element.
Expand All @@ -40,7 +40,7 @@ type Props<Tag extends ElementType> = React.ComponentPropsWithoutRef<Tag> &
* <ImpressionArea
* onImpressionStart={() => console.log('Element entered view')}
* onImpressionEnd={() => console.log('Element exited view')}
* timeThreshold={1000}
* timeThresholdMs={1000}
* areaThreshold={0.5}
* >
* <div>Track me!</div>
Expand All @@ -53,15 +53,15 @@ export const ImpressionArea = forwardRef(ImpressionAreaImpl) as <T extends Eleme
) => React.ReactElement;

function ImpressionAreaImpl<T extends ElementType = 'div'>(
{ as, rootMargin, areaThreshold, timeThreshold, onImpressionStart, onImpressionEnd, ...props }: Props<T>,
{ as, rootMargin, areaThreshold, timeThresholdMs, onImpressionStart, onImpressionEnd, ...props }: Props<T>,
ref: Ref<unknown>
) {
const Component = as ?? 'div';
const impressionRef = useImpressionRef<Element<T>>({
onImpressionStart,
onImpressionEnd,
areaThreshold,
timeThreshold,
timeThresholdMs,
rootMargin,
});

Expand Down
Loading
Loading