Usurper
Usurper

Reputation: 97

How to run useEffect on component mount as well as state changes

I have a useEffect function which runs only when the page state changes, but I want to run this function on both component mount as well as state change.

To accomplish this I used two variables in dependency array

, [page, []]

Using this expression in dependency array shows a warning in the console and the useEffect method runs infinitely, I don't know how to fix this.

My useEffect funtion is

// fetch data from the server when page changes
  useEffect(() => {
    axios
      .get(fetchURL, { headers: { Authorization: AuthStr } })
      .then((response) => {
        // If request is good...
        if (response) {
          setData(response.data);
        }
      })
      .catch((error) => {
        toast.error('Something went wrong, please refresh');
        console.log(error);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [page]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Please suggest a possible solution to this problem.

Upvotes: 3

Views: 4849

Answers (1)

Rishu Trivedi
Rishu Trivedi

Reputation: 48

Your code will run after mount as well as if there is any change in value of "page" which you have passed in the dependency array. Perform some change in "page" and you will see that it will re-render. If there is some other entity that you are using to deduce that there is change in state you should include that also in dependency array.

Upvotes: 3

Related Questions