How can I use useEffect in React to run some code only when the component first mounts, and some other code whenever an event occurs (repeatedly)?

Viewed 57

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!

1 Answers

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
)
Related