DEV Community

Armands
Armands

Posted on

Reactjs - useEffect

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)

Collapse
 
dance2die profile image
Sung M. Kim

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.

As the guide states,

The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API.

In this example from the guide it's expected that count is 0…

Collapse
 
armandsuiska profile image
Armands

I saw that - but it kinda feels like a hack... Thanks for replay.

Collapse
 
jimmytimmons profile image
Jimmy Timmons

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.