Home > Software design >  How to create a trigger function that runs whenever the state changes?
How to create a trigger function that runs whenever the state changes?

Time:10-16

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?

CodePudding user response:

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

  • Related