Reactjs rendering twice

Viewed 5152

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.

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

Related