3

I want to execute code in my useEffect method only when productType is changed, and as soon as page loaded I can recognized console.log is executed more than 6-7 times which is what I don't want.

Here is summary of my code:

const [productType, setProductType] = useState(null); useEffect(() => { console.log(productType); }, productType); 

Idea is to execute code in this useEffect when productType changes, I'm changing it on dropdown like this:

<MyDropdownComponent value={productType} onChange={e => setExportType(e.target.value)} width={200} /> 

So I'm wondering why when I load this view/template, I got like 6-7-8 console.logs of null in my console..

1 Answer 1

2

The useEffect Hook expects an array as second parameter. They probably have done it this way to distinguish an empty array (run effect only once) and the default (run on every render), which they could not have if they would use arguments directly.

You need to pass an array like this:

useEffect(() => { console.log(productType); }, [productType]); 
Sign up to request clarification or add additional context in comments.

5 Comments

thanks in a few sec I'll accept it, you might add some explanation for future readers :) why was my approach wrong etc.
I tried to reason about it, but the main reason is, that the API expects an array. And that is it.
thanks man! And what about if I wanted to execute this code in useEffect even if the productType has same value? (not changed value, for example lets set productType to value of 1, and even if it's 1 again lets execute this.. :))
They you just leave the second parameter out, and it runs on (after) every render. But if you call setProductType with the previous value react will not cause a render and therefore your effect will also not be called, only if some other values change. If you want to force an render you could introduce another state variable for example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.