kxd-react-route-cache
Version:
change color from react-route-cache for my project
26 lines (25 loc) • 901 B
JavaScript
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;
callback();
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]);
};