Hello I am learning about the useEffect hook in react, and I need some clarification. It is my understand that when we provide an empty dependency array that the code inside of the useEffect hook will only run once during the application's initial mount. I need some helping understand why the code below runs every time I refresh the page even though I provided an empty dependency array?
Thank you
const [numberOfVistors, setnumberOfVistors] = useState(() => {
localStorage.getItem("numberOfVistorsKey")
});
useEffect (() => {
let vistorCount = localStorage.getItem("numberOfVistorsKey")
if (vistorCount > 0)
{
vistorCount = Number(vistorCount) 1
localStorage.setItem("numberOfVistorsKey", vistorCount)
setnumberOfVistors(vistorCount)
}
else
{
vistorCount = 1
setnumberOfVistors(vistorCount)
localStorage.setItem("numberOfVistorsKey", vistorCount)
}
}, [])
CodePudding user response:
The context of an application does not persist across multiple pageloads or refreshes except through the few ways that allow for persistent data - such as local storage, cookies, and an API with a server somewhere. For the same reason, doing
let num = 5;
button.onclick = () => { num = 10; }
results in num
still being 5 after you click and reload the page - because reloading the page starts the script from the very beginning again, on the new page.
If you want to keep track of whether that particular section of code has ever run before, use a flag in storage, eg:
useEffect(() => {
if (localStorage.hasVisitedBefore) return;
localStorage.hasVisitedBefore = 'yes';
// rest of effect hook
, []);
CodePudding user response:
I need some helping understand why the code below runs every time I refresh the page even though I provided an empty dependency array?
Every time you refresh the page, the React component mounts for the first time.
CodePudding user response:
useEffect(..., [])
was supplied with an empty
array as the dependencies argument. When configured in such a way, the useEffect()
executes the callback just once, after initial mounting
.
CodePudding user response:
Whenever you refresh the page, React component will be re-rendered. Therefore useEffect() is called everytime. In order to avoid it, you have to do like this.
const [numberOfVistors, setnumberOfVistors] = useState(() => {
localStorage.getItem("numberOfVistorsKey")
});
useEffect (() => {
let vistorCount = localStorage.getItem("numberOfVistorsKey")
if (vistorCount > 0)
{
vistorCount = Number(vistorCount) 1
localStorage.setItem("numberOfVistorsKey", vistorCount)
setnumberOfVistors(vistorCount)
}
else
{
vistorCount = 1
setnumberOfVistors(vistorCount)
localStorage.setItem("numberOfVistorsKey", vistorCount)
}
}, [numberOfVistors])
This code will render your component whenever numberOfVistors are changed.