UNPKG

react-route-cache

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