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?
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.
“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.
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.
Below is the example of useEffect having multiple dependencies. Console. log(“This useEffect will run either data or siteUrl changes”, data, siteUrl); }, [data, siteUrl]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With