Reputation: 542
If the title wasn't clear, I want to run some code when the component mounts, and some other code when a particular variable changes. I could add the variable in the [], but the problem is, I want some code to run only once, and not when the variable changes.
FYI: The variable is a window property
Thanks in advance!
Upvotes: 3
Views: 97
Reputation: 12174
Have two separate effects to handle each case.
Case 1: when the component mounts
useEffect(
() => {
// do something
},
[] // no dependency: run once
)
Case 2: when the variable changes
useEffect(
() => {
if (variable) {
// do something
}
},
[variable] // with dependency: run every time variable changes
)
Upvotes: 3