JesseSousa
JesseSousa

Reputation: 25

How to create a trigger function that runs whenever the state changes?

I'm using localStorage for my project, and I want to update the localStorage everytime the state changes. I've read the documentation and I found a lifecycle method called shouldComponentUpdate() so I have two questions. Is it possible to be used in a functional component? and Is there a better way to do it?

Upvotes: 0

Views: 382

Answers (1)

gungor
gungor

Reputation: 124

Does your react version have react hooks? If yes you can use the code below

useEffect(() => {
// change the localStorage
}, [state]);

this hook listens for updates of the variable inside the square brackets

Upvotes: 1

Related Questions