All files / src/hooks usePlayerPref.ts

100% Statements 9/9
100% Branches 0/0
100% Functions 4/4
100% Lines 7/7

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                    3x 4460x 4460x 651x 651x 651x   4460x    
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
 
import { useEffect, useState } from "react";
 
/**
 * A player preference from `player-prefs`, read again each time Settings
 * fires `event` for it. `read` should be a module-level function, so the
 * listener isn't added again on every render.
 */
export const usePlayerPref = <T>(read: () => T, event: string): T => {
	const [value, setValue] = useState(read);
	useEffect(() => {
		const update = () => setValue(read());
		window.addEventListener(event, update);
		return () => window.removeEventListener(event, update);
	}, [read, event]);
	return value;
};