2023-02-15 16:20:58 -05:00
|
|
|
/*
|
2024-09-06 10:22:13 +02:00
|
|
|
Copyright 2024 New Vector Ltd.
|
2023-02-15 16:20:58 -05:00
|
|
|
|
2025-02-18 17:59:58 +00:00
|
|
|
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
2024-09-06 10:22:13 +02:00
|
|
|
Please see LICENSE in the repository root for full details.
|
2023-02-15 16:20:58 -05:00
|
|
|
*/
|
|
|
|
|
|
2024-12-11 09:27:55 +00:00
|
|
|
import { type RefObject, useRef } from "react";
|
2023-01-18 10:52:12 -05:00
|
|
|
|
2024-05-02 18:44:36 -04:00
|
|
|
export interface LatestRef<T> extends RefObject<T> {
|
2025-02-24 17:45:40 +07:00
|
|
|
current: T; // Always defined, unlike RefObject["current"]
|
2023-01-18 10:52:12 -05:00
|
|
|
}
|
|
|
|
|
|
2024-05-02 18:44:36 -04:00
|
|
|
/**
|
|
|
|
|
* React hook that returns a ref containing the value given on the latest
|
2025-02-24 17:45:40 +07:00
|
|
|
* render. Useful for accessing the latest value of something in an effect or
|
|
|
|
|
* callback when you don't want reactivity.
|
2024-05-02 18:44:36 -04:00
|
|
|
*/
|
|
|
|
|
export function useLatest<T>(value: T): LatestRef<T> {
|
|
|
|
|
const ref = useRef<T>(value);
|
|
|
|
|
ref.current = value;
|
|
|
|
|
return ref;
|
2023-01-29 21:56:07 -05:00
|
|
|
}
|