@itwin/core-react
Version:
A react component library of iTwin.js UI general purpose components
54 lines • 2.31 kB
JavaScript
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Utilities
*/
import { useEffect, useRef, useState } from "react";
/**
* A custom hook which creates a disposable object and manages its disposal on unmount
* or factory method change.
* @public
* @deprecated in 4.9.0. This hook is not compatible with React 18 Strict mode. Use [[useOptionalDisposable]] or `useState` + `useEffect` for
* creating and disposing disposable resources.
*/
// eslint-disable-next-line @typescript-eslint/no-deprecated
export function useDisposable(createDisposable) {
const [value, setValue] = useState(() => createDisposable());
// need to capture initial disposable created during render loop in order to dispose later
const prevValue = useRef(value);
const useInitialValue = useRef(true);
useEffect(() => {
// do not create new disposable on initial render. It was created during render loop.
if (!useInitialValue.current) {
prevValue.current = createDisposable();
setValue(prevValue.current);
}
useInitialValue.current = false;
return () => {
prevValue.current.dispose();
};
}, [createDisposable]);
return value;
}
/**
* A custom hook which calls the factory method to create a disposable object
* which might as well be undefined. If the result was a disposable object, the
* hook takes care of disposing it when necessary.
* @public
* @deprecated in 4.15.0. Use `useState` + `useEffect` for creating and disposing disposable resources.
*/
// eslint-disable-next-line @typescript-eslint/no-deprecated
export function useOptionalDisposable(createDisposable) {
const [value, setValue] = useState();
useEffect(() => {
const disposable = createDisposable();
setValue(disposable);
return () => {
disposable && disposable.dispose();
};
}, [createDisposable]);
return value;
}
//# sourceMappingURL=useDisposable.js.map