All files / src/hooks useLatestRef.ts

100% Statements 5/5
100% Branches 0/0
100% Functions 2/2
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23                              30x 23707x 23707x 20131x   23707x    
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
 
import { useInsertionEffect, useRef } from "react";
 
/**
 * A ref holding the newest `value`, for timers, listeners and callbacks that
 * outlive the render they came from. It's the same object on every render, so
 * it never makes an effect run again.
 *
 * The value is copied in once React commits the render, so read it in effects
 * and event handlers rather than while rendering. An insertion effect runs
 * before every layout effect, so a child's layout effect that calls back into
 * its parent already sees the parent's new value.
 */
export const useLatestRef = <T>(value: T): { readonly current: T } => {
	const ref = useRef(value);
	useInsertionEffect(() => {
		ref.current = value;
	});
	return ref;
};