Dark Programmer
Dark Programmer

Reputation: 542

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

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

Answers (1)

Joseph D.
Joseph D.

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

Related Questions