3

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.

2
  • 4
    It will render twice, so what's the problem? this is how api call works Commented Jan 4, 2019 at 8:56
  • 2
    Please explain why you think that the component being rendered multiple times is somehow bad. Because that's how React works (or any other software that uses a screen). Commented Jan 4, 2019 at 9:02

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Good answer, but shouldn't we find out why OP thinks that a non-problem is a problem first? I fear that telling them about shouldComponentUpdate might encourage a bad practice that should be avoided in the first place.
@ChrisG yes you are right, However, I did try to explain what exactly is happening in the OP code, and advised on using PureComponent instead of implementing shouldComponentUpdate himself

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.