I'm learning about the React
useEffect
hook, especially the dependency array
. Having such simple counter:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, []); // Only re-run the effect if count changes!?
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>You clicked {count} times!</h2>
<button onClick={() => setCount(count - 1)}>Decrement</button>
<button onClick={() => setCount(count 1)}>Increment</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Even if the dependency array
is empty the counter still works - the counter value is still increased/decreased when I click the button.
As far as I understand from the doc, setting the dependency array
empty should just disable the useEffect
to run if the dependency array doesn't explicitly list/include the changing value.
CodePudding user response:
useEffect
either runs on every render (if you do not use a dependency array) or once every time the dependency array changes.
On first render, the dependency array always changes from "no prior call" to "this is my dependency array" - useEffect
will always be executed on the first render. If your dependency array is empty it will just not be executed any more after that.
CodePudding user response:
First of all useEffect
hook runs only once in component life cycle as far as you understand it unless you specify something in dependency array. Now for your question that why the counter is still updating that is because you are using useState
which is hook responsible for updating the value in screen and has nothing to do with useEffect hook
And to make sure console.log("i run only once") in useEffect hook and you will see that it runs only one time and counter value also doesn't get increased or decreased