🌟
Next.jsでchange stateのイベントハンドリングしたいとき
Next.js で change state のイベントハンドリングしたいとき
router.events
を使えばいい
function App({ Component, pageProps }) {
const router = useRouter();
const [loading, setLoading] = useState(false);
const handleStart = (url) => {
if (url !== router.pathname) {
setLoading(true);
}
};
const handleComplete = (url) => {
if (url !== router.pathname) {
setLoading(false);
}
};
useEffect(() => {
router.events.on("routeChangeStart", handleStart);
router.events.on("routeChangeComplete", handleComplete);
router.events.on("routeChangeError", handleComplete);
return () => {
router.events.off("routeChangeStart", handleStart);
router.events.off("routeChangeComplete", handleComplete);
router.events.off("routeChangeError", handleComplete);
};
}, []);
return <div />;
}
Discussion