3

Before React hooks, I would use componentDidUpdate(prevProps, prevState), and if I wanted to execute given code only when this.state.a had updated, I'd do

if (prevState.a !== this.state.a) {
  <...>
}

How can I achieve the same thing in useEffect()?

gkeenley
  • 6,088
  • 8
  • 54
  • 129
  • I found this ***amazing*** [resouce](https://reactjs.org/docs/hooks-effect.html) that explains the `useEffect` hook. Seems also others here may've missed the part that you want to compare to a previous value. – Drew Reese May 28 '21 at 20:47

4 Answers4

6

The useEffect function takes a dependency array where you can mention the states you want to track for change.

useEffect(() => {
    //your code here
}, [a])
Prayag Choraria
  • 710
  • 5
  • 15
2

useEffect takes the second argument called as a dependency array . You can pass your state here and this gets executed whenever the value in the dependency array changes .

useEffect(() => {
   console.log('i get executed whenever a changes')
}, [a]) 
Shyam
  • 5,292
  • 1
  • 10
  • 20
1
useEffect(() => {
//Your code
}, [stateOne, stateTwo])

[stateOne, stateTwo] means that if any of the state variables defined inside change, the useEffect will run. Also runs for the fist time once it mounts.

[] means that it will run only once

It is called an dependency array for useEffect.

SlothOverlord
  • 1,655
  • 1
  • 6
  • 16
  • So if I have state variables `a`, `b`, and `c`, I could write a `useEffect` for each of them? – gkeenley May 28 '21 at 13:57
  • Yup. You can have as many as you want. You can either include multiple variables in One dependency array, so if ANY of them change, the useEffect will run, or you can have separate useEffects for your variables. Just note that if you have a dependency array in your useEffect, it will still run for the fist time when your component mounts. – SlothOverlord May 28 '21 at 14:13
0

useEffect takes a second parameter called dependency array. You can pass your state variable here and useEffect will execute the callback function only when that state variable changes.

const [a, setA] = useState(0);
useEffect(() => {
    //write you code here
}, [a]);