1

I have a User Page that fetch the user info with a custom hook useFetchUserId(). This custom hook uses useEffect to fetch the data, and has a console.log that is printed every time I switch between tabs, even if I use the useCallback hook. Can you explain why, and how to fix it?

UserProfile page:

  const location = useLocation();
  const userId = location.state?.userId;
  const [tab, setTab] = useState("1");
  const { user, loading } = useFetchUserId(userId);

  const handleTabChange = useCallback(function handleTabChange(event, newTab) {
    setTab(newTab);
  }, []);

  return (
          <TabList onChange={handleTabChange} aria-label="lab API tabs example">
            <Tab label="Info" value="1" />
            <Tab label="Cambia Password" value="2" />
            <Tab label="Curriculum" value="3" />
          </TabList>
        

useFetchUserId:

 export const useFetchUserId = (id) => {
  const [user, setUser] = useState([]);
  const [loading, setLoading] = useState(false);
  console.log("fetch  " + id);

  useEffect(() => {
    const fetch = async () => {

      try {
        const response = await axios....
        const result = response?.data;
        if (result) {
          setUser(result);
        }
      } catch (err) {
        console.log(err);
      } 
    };
    fetch();
    
  }, []);

  return { user, loading };
};
Giovanni
  • 512
  • 2
  • 6
  • 23
  • 1
    Unless I'm missing something, you're modifying the state of your component so it needs to rerender – Axnyff Mar 11 '23 at 15:27
  • ok, it's true. Can I avoid to call the useFetchUserId, when I change tab? Maybe handle the tabs state in a different component? – Giovanni Mar 11 '23 at 15:29
  • The problem probably lies within useFetchUserId: its useEffect should be modified to only fetch on the right conditions. Can you show its code ? – Axnyff Mar 11 '23 at 15:30
  • I just Updated the code – Giovanni Mar 11 '23 at 15:33
  • Nothing looks wrong in your useFetchUserId, I think your UserProfile must be getting unmounted for some reason. You can verify that by adding `useEffect(() => { console.log("Mounting"); return () => console.log("Unmounting"); }, []);` – Axnyff Mar 11 '23 at 15:37
  • No it does not. only when I first open the Profile page the console is: "fetch user" "fetch user" "Mounting" "Unmounting" "Mounting". Then when I swith tab, same beavior. re-render 2 times – Giovanni Mar 11 '23 at 15:43
  • 1
    There's something wrong if you see Unmounting being logged, that means the useEffect will be retriggered – Axnyff Mar 11 '23 at 15:52

2 Answers2

1

You change state by setTab(newTab). It triggers re-render (aka re-execution of component function). This way your hook useFetchUserId is executed every time. This is why you see a console log multiple times. See the console.log outside of useEffect.

hastrb
  • 410
  • 4
  • 12
0

Check what are you send dependencies in useEffect, if use user as dependency remove this

  • 1
    His dependencies list of `useEffect` is empty. That's not a reason. – hastrb Mar 11 '23 at 15:44
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 19 '23 at 13:02