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

1
  • I found this amazing resouce that explains the useEffect hook. Seems also others here may've missed the part that you want to compare to a previous value. Commented May 28, 2021 at 20:47

4 Answers 4

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])
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

2 Comments

So if I have state variables a, b, and c, I could write a useEffect for each of them?
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.
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]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.