Why my React component rendering multiple times

Viewed 4897

I'm trying to add protected routes in App.js for authenticated users but the react element is getting rendered multiple times. Below is my App.js code

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentUser: null,
      isAuthenticated: false,
      isLoading: false
    }
  }
  async loadCurrentUser() {
    this.setState({
      isLoading: true
    });
    await getCurrentUser()
      .then(response => {
        this.setState({
          currentUser: response,
          isAuthenticated: true,
          isLoading: false
        });
      }).catch(error => {
        this.setState({
          isLoading: false
        });
      });
  }
  async componentDidMount() { await this.loadCurrentUser(); } render() {
    return (
      <BrowserRouter>
        <React.Suspense fallback={loading}>
          <Switch>
            <Route exact path="/login" component={Login} />
            <Route exact path="/register" component={Register} />
            <ProtectedRoute path="/" name="Home" authenticated={this.state.isAuthenticated}
              component={TheLayout} handleLogout={this.handleLogout}></ProtectedRoute>
          </Switch>
        </React.Suspense>
      </BrowserRouter>
    );

  }
}   
1 Answers

In React, a component re-render occurs when one of two conditions is met: When the props of the component change(i.e, when the parent component passes new props), or when the state is updated. In your case, when your component mounts for the first time, your loadCurrentUser is called, which first sets state(isLoading = true), causing a rerender, and then sets state again, causing another re-render for a total of three renders including the initial render. So if your logs are showing the same number of renders, that is expected behaviour, but if it is re-rendering more than 3 times, check your parent component to see if it is changing the props being passed to this component(I doubt that's the case here, since App component is traditionally the topmost component with no other parent components.

Related