Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks: how to detect when particular state variable has updated [duplicate]

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

like image 650
gkeenley Avatar asked Apr 30 '26 04:04

gkeenley


1 Answers

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

useEffect(() => {
    //your code here
}, [a])
like image 106
Prayag Choraria Avatar answered May 02 '26 19:05

Prayag Choraria



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!