Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does [history.push] in useEffect dependency array cause rerenders?

Can't find documentation about this anywhere. Will this cause the useEffect to EVER run again? I don't want it to fetch twice, that would cause some issues in my code.

import React, { useEffect } from 'react'
import { useHistory } from 'react-router-dom'

const myComponent = () => {
  const { push } = useHistory();

  useEffect( () => {
    console.log(" THIS SHOULD RUN ONLY ONCE ");
    fetch(/*something*/)
      .then( () => push('/login') );
  }, [push]);
  

  return <p> Hello, World! </p>
}

From testing, it doesn't ever run twice. Is there a case that it would?

For the sake of the question, assume that the component's parent is rerendering often, and so this component is as well. The push function doesn't seem to change between renders - will it ever?

like image 922
Adelbert Ames Avatar asked Aug 07 '20 13:08

Adelbert Ames


People also ask

What happens if we don't pass dependency array in useEffect?

Empty dependency array So what happens when the dependency array is empty? It simply means that the hook will only trigger once when the component is first rendered. So for example, for useEffect it means the callback will run once at the beginning of the lifecycle of the component and never again.

How do you use history PUSH IN React hooks?

“useHistory()” hook returns the history instance created by React Router, and history. push(“/profile/John”) adds the given URL to the history stack which results in redirecting the user to the given URL path. Similarly, you can use other methods and parameters of the history object as per your need.

What if dependency array is empty in useEffect?

If it's empty ( [] ), the effect runs once, after the initial render. It must — or as we'll see later, should — contain the list of values used in the effect. The effect runs after any of these values changes (and after the initial render). The array of dependencies is not passed as argument to the effect function.

Can a useEffect have multiple dependencies?

Below is the example of useEffect having multiple dependencies. Console. log(“This useEffect will run either data or siteUrl changes”, data, siteUrl); }, [data, siteUrl]);


1 Answers

Ciao, the way you write useEffect is absolutely right. And useEffect will be not triggered an infinite number of time. As you said, push function doesn't change between renders.

So you correctly added push on useEffect deps list in order to be called after fetch request. I can't see any error in your code.

like image 106
Giovanni Esposito Avatar answered Sep 20 '22 23:09

Giovanni Esposito