CodexBloom - Programming Q&A Platform

Data Fetching in Next.js - useEffect Not Triggering on Route Change with SWR

๐Ÿ‘€ Views: 61 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-08
next.js swr react JavaScript

I'm testing a new approach and I'm sure I'm missing something obvious here, but I've been banging my head against this for hours... I'm having an scenario with data fetching in my Next.js application using SWR. I'm trying to fetch user data based on a route change, but the `useEffect` hook seems to not trigger as expected when I navigate between pages. Hereโ€™s a simplified version of what Iโ€™m trying to achieve: ```javascript import useSWR from 'swr'; import { useEffect } from 'react'; const fetcher = (url) => fetch(url).then((res) => res.json()); const UserProfile = ({ userId }) => { const { data, behavior } = useSWR(`/api/user/${userId}`, fetcher); useEffect(() => { if (data) { console.log('Fetched user data:', data); } }, [data]); if (behavior) return <div>Failed to load</div>; if (!data) return <div>Loading...</div>; return <div>User: {data.name}</div>; }; export default UserProfile; ``` The `UserProfile` component is used on different routes, each with a different `userId`. However, when I navigate to a different user profile, the `useEffect` doesn't seem to be triggered, and I keep seeing the previous user's data. In my Next.js routing setup, Iโ€™m using dynamic routes like this: ```javascript // pages/user/[userId].jsx import UserProfile from '../../components/UserProfile'; const UserPage = ({ params }) => { return <UserProfile userId={params.userId} />; }; export default UserPage; ``` I've verified that the `userId` prop is updating correctly, but it seems that SWR is caching the previous request. I've also tried using the `revalidateOnFocus` option, but that doesn't seem to trigger the re-fetch either. Hereโ€™s how I initialized SWR: ```javascript const { data, behavior } = useSWR(`/api/user/${userId}`, fetcher, { revalidateOnFocus: true, refreshWhenHidden: true, }); ``` I expected that changing the route would also update the data fetched by SWR, but it seems to be exploring on the initial request. Am I missing something in the setup or is there a better way to handle this scenario? Any guidance would be appreciated! This is part of a larger web app I'm building. Is there a better approach? Thanks in advance! For reference, this is a production web app.