Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs rendering twice

In my reactjs project, component is rendered twice. if I remove the componentDidMount, the problem is fixed. But I need it in my project. I tried the solutions on the internet, but I couldn't.

App.js

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: []
    };
  }
  componentDidMount() {
    fetch("https://reqres.in/api/users?page=2")
      .then(res => res.json())
      .then(result => {
        this.setState({
          users: result.data
        });
      });
  }

  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path="/" render={() => <Home />} />
        </Switch>
      </BrowserRouter>
    );
  }
}

Home.js

export default class Home extends Component {
  render() {
    console.log("Render");
    return (
      <div>
        <h1>console.log render twice</h1>
      </div>
    );
  }
}

https://codesandbox.io/s/wyjk931z6l

console.log works on Home.js twice.

like image 884
tom clarck Avatar asked Apr 15 '26 17:04

tom clarck


1 Answers

You App component re-renders because the API call that you make in componentDidMount results in a setState on success. Due to this, the child components also go though a re-render even though their props didn't change. In order to avoid it, you can write the child component by extending React.PureComponent which implements the shouldComponentUpdate by shallowly comparing the props and state.

export default class Home extends PureComponent {
  render() {
    console.log("Render");
    return (
      <div>
        <h1>console.log render twice</h1>
      </div>
    );
  }
}

Working demo

like image 86
Shubham Khatri Avatar answered Apr 17 '26 06:04

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!