0

I came across this class component with 2 lifecycle methods handling the component's side-effects after each re-render:
componentDidMount and componentDidUpdate
I copied the example (at the bottom) and tried to play with it by deleting componentDidUpdate to see what would happen if I don't handle side-effects on every re-render. But nothing seems to break; the button still increments the state.
If I am not mistaken, the React documentation says the side-effect needed to be handled in each re-render even if it leads to duplication. I wonder what bad things can happen if we didn't.

import React from "react";
import "./styles.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }
  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}
Eddie Lam
  • 579
  • 1
  • 5
  • 22
  • Can you link to the documentation you have seen? There's no such rule. In fact, it's better to have side effect code run once only. In your case it didn't matter because the side effect was idempotent. – Mukesh Soni Oct 12 '20 at 11:05
  • sure. https://reactjs.org/docs/hooks-effect.html look for "Note how we have to duplicate the code between these two lifecycle methods in class." – Eddie Lam Oct 12 '20 at 11:11
  • That is relevant when you want to run the side effect during "first mount" and the subsequent "updates'. They don't run twice on every render. – Mukesh Soni Oct 12 '20 at 11:23

0 Answers0