@nexcodepl/store-react
Version:
React utils for @nexcodepl/store
29 lines (28 loc) • 1.05 kB
JavaScript
import { useRef, useEffect } from "react";
import { StoreEffect } from "@nexcodepl/store";
import { getDependencies } from "./utils.js";
import { useRefStatic } from "./useRefStatic.js";
export function useStoreEffect(effect, dependencies) {
const { storeDependencies, nonStoreDependencies } = getDependencies(dependencies);
const effectDestructorRef = useRef(undefined);
const effectRef = useRefStatic(() => new StoreEffect(() => callEffect(), storeDependencies));
useEffect(() => {
if (nonStoreDependencies.length === 0)
return;
return callEffect();
}, nonStoreDependencies);
useEffect(() => {
effectRef.current.dependenciesSubscribe();
return () => {
effectRef.current.dependenciesUnsubscribe();
};
}, []);
function callEffect() {
effectDestructorRef.current = effect() ?? undefined;
return () => {
if (!effectDestructorRef.current)
return;
effectDestructorRef.current();
};
}
}