Home > Net >  React useEffect not being triggered for default state
React useEffect not being triggered for default state

Time:11-08

When I try to set the page to the default value from refresh function, it doesn't trigger the useEffect hook. But if I run the refresh function 2nd time it works fine. And this code also works fine for other values like 2, 3, 4, 5......

  const [goal, setGoal] = useState();
  const [page, setPage] = useState(1);
  const [temp, setTemp] = useState([]);

  useEffect(() => {
    setGoal();
    getData();
  }, [page]);

  const refresh = () => {
    setTemp([]);
    setPage(1);
  };

CodePudding user response:

If page already has value "1" then refresh won't trigger useEffect, there must be some other value in "page" state to make "setPage(1)" update it, and then if the state updates it will trigger useEffect.

CodePudding user response:

For "refreshing" purposes it is actually a better idea to have separated state exactly for triggering re-rendering cycle in React

const [counter, setCounter] = useState(0)

const refresh = () => setCounter(counter   1)

and then make your useEffect dependant on counter value

  • Related