React component being called twice

Viewed 588

The Portal component is being called twice.

Why is it happening?

How can I prevent that?


index.js

const App = () => {
  const theme = lightTheme;

  return (
    <Provider store={store}>
      <StyleSheetManager>
        <ThemeProvider theme={theme}>
          <BrowserRouter>
            <Portal />
          </BrowserRouter>
          <GlobalStyle />
        </ThemeProvider>
      </StyleSheetManager>
    </Provider>
  );
};

ReactDOM.render(<App />, document.getElementById("app"));

Portal.jsx

class Portal extends React.Component {
  isAuthenticated = () => {
    if (this.props.tokenized) {
      return (
        <React.Fragment>
          <Sidebar />
          <MainContainer />
          <Switch>
            <Route exact path="/"></Route>
          </Switch>
        </React.Fragment>
      );
    } else {
      return <Authorize />;
    }
  };

  render() {
    this.props.dispatch(checkToken());
    return (
      <React.Fragment>
        <Alerts />
        {this.isAuthenticated()}
      </React.Fragment>
    );
  }
}

export default connect(
  ({ authenticator }) => ({
    tokenized: authenticator.tokenized,
  }),
  null
)(Portal);
1 Answers

This happens as you're dispatching an action on every render and the redux state is probably getting updated after the first dispatch call to it.

When your Portal renders for the first time, yu dispatch checkToken() which checks for token probably and updates authenticator.tokenized. Since your component is connected to the store to map state to props, your prop tokenized carries a new value therefore causing a re-render. BUT, rendering twice of this particular component is not erronuous as the token can be only avilable after some time(after the first render of the component).

You should memoize the component so that you can perform checks to incoming props with previous props to avoid unnecessary re-renders.

Also, your checkToken call should happen only once when the component loads (in componentDidMount) and not everytime in each render method execution.

Related