UNPKG

@carbon/react

Version:

React components for the Carbon Design System

40 lines (38 loc) 1.11 kB
/** * Copyright IBM Corp. 2016, 2026 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import { useCallback, useEffect, useRef, useState } from "react"; //#region src/internal/useDelayedState.ts /** * Copyright IBM Corp. 2016, 2023 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ function useDelayedState(initialState) { const [state, setState] = useState(initialState); const timeoutId = useRef(null); const setStateWithDelay = useCallback((stateToSet, delayMs = 0) => { window.clearTimeout(timeoutId.current ?? void 0); timeoutId.current = null; if (delayMs === 0) { setState(stateToSet); return; } timeoutId.current = window.setTimeout(() => { setState(stateToSet); timeoutId.current = null; }, delayMs); }, []); useEffect(() => { return () => { window.clearTimeout(timeoutId.current ?? void 0); }; }, []); return [state, setStateWithDelay]; } //#endregion export { useDelayedState };