react-native-filament
Version:
A real-time physically based 3D rendering engine for React Native
46 lines (45 loc) • 1.65 kB
JavaScript
import { useEffect, useState } from 'react';
import { withCleanupScope } from '../utilities/withCleanupScope';
const emptyStaticArray = [];
/**
* Any resource that is a {@link PointerHolder} and can be released, should be loaded
* using this hook. It takes care of properly releasing the resource when the component
* unmounts or dependencies change.
* There are certain cases like "fast refresh" or StrictMode that make useEffects execute
* multiple times. Also loading the resource can be async and this hooks handles all these
* cases properly.
*/
export const useDisposableResource = (initialize, deps) => {
const [resource, setResource] = useState();
useEffect(() => {
var _initialize;
let isValid = true;
let currentAsset;
(_initialize = initialize()) === null || _initialize === void 0 || _initialize.then(a => {
if (a == null) return;
if (isValid) {
// this useEffect is still mounted
setResource(a);
currentAsset = a;
} else {
// this useEffect has been unmounted already, drop the asset
a.release();
}
});
// TODO: catch is broken
// .catch((e) => {
// console.error('Error while loading resource', e)
// })
return () => {
setResource(undefined);
isValid = false;
withCleanupScope(() => {
var _currentAsset;
(_currentAsset = currentAsset) === null || _currentAsset === void 0 || _currentAsset.release();
})();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps ?? emptyStaticArray);
return resource;
};
//# sourceMappingURL=useDisposableResource.js.map