Reactjs – Best way to update react ‘dirty’ state within component


If I have a react component that will pop up a "Are you sure" confirm modal if the state is dirty, what is the most convenient way to mark dirty? I have a basic local array state of objects that can have their values changed, and items deleted/added. Right now I have a setState({dirty: true}) in valuesChanged(), addItem(), deleteItem(), toggleSwitch(), etc. I know there is a less redundant way to accomplish this, perhaps comparing state in a component life cycle. I am just not sure how to do it.

Best Solution

React 17.0 will be removing componentWillReceiveProps lifecycle hook (and a couple of others) and will begin the deprecation process in React 16.3. See this github issue for some more information. There's a blog post coming too.

So with that said, you could do something like this:

componentDidUpdate(prevProps, prevState) {    //add whatever comparison logic you need here    if(this.state.someValue !== prevState.someValue && !this.state.dirty) {        this.setState({ dirty: true });    }    //optionally you could also reset dirty here if you also    //persisted the original values and the user undid their    //changes}