@theoplayer/react-native-ui
Version:
A React Native UI for @theoplayer/react-native
42 lines (41 loc) • 1.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useThrottledState = useThrottledState;
var _react = require("react");
/**
* A throttled version of React's `useState` that limits how often the state is updated.
*
* When `setValue` is called repeatedly, the state will update immediately if enough time
* has passed since the last update. Otherwise, it schedules an update after the remaining
* throttle interval. The most recent value is always applied eventually (trailing flush).
*
* @param initialValue The initial state value.
* @param intervalMs The minimum interval (in milliseconds) between state updates.
* @returns A tuple of `[state, setValue]`, just like `useState`.
*/
function useThrottledState(initialValue, intervalMs) {
const [state, setState] = (0, _react.useState)(initialValue);
const lastExecuted = (0, _react.useRef)(0);
const timeoutRef = (0, _react.useRef)();
const setThrottled = (0, _react.useCallback)((value, forced = false) => {
const now = Date.now();
const timeSinceLast = now - lastExecuted.current;
clearTimeout(timeoutRef.current);
if (forced || timeSinceLast >= intervalMs) {
setState(value);
lastExecuted.current = now;
} else {
timeoutRef.current = setTimeout(() => {
setState(value);
lastExecuted.current = Date.now();
}, intervalMs - timeSinceLast);
}
}, [intervalMs]);
(0, _react.useEffect)(() => {
return () => clearTimeout(timeoutRef.current);
}, []);
return [state, setThrottled];
}
//# sourceMappingURL=useThrottledState.js.map