Zahin Afsar
Zahin Afsar

Reputation: 441

React useEffect not being triggered for default state

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);
  };

Upvotes: 0

Views: 1824

Answers (3)

Abdullah Manafikhi
Abdullah Manafikhi

Reputation: 68

This is the easiest way to re-run the useEffect

 const [refresh, setRefresh] = useState(false);

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

  //whenever you want to refresh just use this 
  setRefresh(!refresh)

Upvotes: 0

JSEvgeny
JSEvgeny

Reputation: 2750

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

Upvotes: 0

Umar
Umar

Reputation: 94

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.

Upvotes: 1

Related Questions