Timeout function behaving inconsistently (React)

I have a function within a component in React, and these are the final two lines:

this.setState({notificationStyle: {display:"inline"}})
    setTimeout(() => this.setState({notificationStyle: {display: "none"}}),2000)

It controls a pop-up notification which informs the user their action was successful. First it sets the notification’s display property to inline/visible – then 2 seconds later the Timeout function should set it to none/invisible again.

However it’s really inconsistent, sometimes it’s up for 2 seconds, sometimes it’s barely a flash, sometimes somewhere in between. I wondered if something is interrupting it, but I thought React was synchronous by default and it should finish executing the Timeout function before moving onto anything else?

I don’t have any (deliberate) async code elsewhere in the application… any ideas? Thank you 🙂

Answer

put that setTimeout inside a useEffect and you’re golden.