Hi, I have some questions about reactjs useEffect hook.
if in my function component I write something like this:
const [myValue, setMyValue] = useState("initialValue");
useEffect(() => { console.log("Call this one time"); }, []);
useEffect(() => { console.log("Call when data changed"); }, [myValue]);
When I render component for first time I get both console logs. But WHY? When I pass empty array react knows that it should execute this callback once. Why it checks passed array values in initial rendering? Now it is not possible to execute second effect only when data has changed...
Top comments (4)
useEffect
is run on every render. So initially both will run and on next render, React will check deps array to see if an effect should run.If what you are trying to skip the initial render, check out this Stackoverflow for workarounds.
answer re: With useEffect, how can I skip applying an effect upon the initial render?
As the guide states,
In this example from the guide it's expected that
count
is 0β¦I saw that - but it kinda feels like a hack... Thanks for replay.
This part of the docs seems to address what you're asking - reactjs.org/docs/hooks-faq.html#ca...
Some comments may only be visible to logged-in visitors. Sign in to view all comments.