UNPKG

@vgbire/react-keep-alive

Version:
25 lines (24 loc) 895 B
import { useEffect, useId } from 'react'; import { useLocation } from 'react-router'; import { useKeepAliveContext } from '..'; export const useDeactivated = (callback, deps = []) => { const { deactivateds, setDeactivateds } = useKeepAliveContext(); const { pathname } = useLocation(); const id = useId(); useEffect(() => { callback.id = id; if (!deactivateds[pathname]) { deactivateds[pathname] = []; } const index = deactivateds[pathname].findIndex((item) => item.id === id); if (index !== -1) { deactivateds[pathname].splice(index, 1); } deactivateds[pathname].push(callback); setDeactivateds(Object.assign({}, deactivateds)); return () => { delete deactivateds[pathname]; setDeactivateds(Object.assign({}, deactivateds)); }; }, [...deps]); };