Sachin Jain
Sachin Jain

Reputation: 21842

React Router v4 rendering component twice

Here is my Router Implementation

<BrowserRouter>
  <div>
    <Route exact path="/" component={ProfilesIndex} />
    <Route exact path="/profiles" component={ProfilesIndex} />
    <Route exact path="/profiles/new" component={ProfileEditor} />
    <Route exact path="/profiles/:id" component={ProfileEditor} />
  </div>
</BrowserRouter>

When I am browsing to /profiles/new path, it is rendering the ProfileEditor component twice. For every other route, it is working fine.

Can someone suggest how to fix this problem ?

Upvotes: 10

Views: 12394

Answers (3)

for me, this is because of React.StrictNode which is wrapped arround App component.

it intentionally double render components (only in development) to enforce you, not use side effects on some of your component's lifecycle events.

the reason behind that is documented here

Upvotes: 13

nanobar
nanobar

Reputation: 66395

For anyone coming here from v6+

exact prop no longer exists, the paths are exact by default if they aren't appended a wildcard *

However I was still getting a double render. I ran a prod build and checked and the double render is gone so probably nothing to worry about - sometimes hooks run twice in development mode (I guess that's what's happening internally)

Upvotes: 8

Sachin Jain
Sachin Jain

Reputation: 21842

I found the answer after browsing into multiple sections in Router Docs. Problem was it was matching multiple routes

When user opens /profiles/new it matches two routes

  1. /routes/new
  2. /routes/:id

Because :id is like a wildcard * and it also matches new word so both routes get matched and hence the component gets rendered twice.

The solution is to wrap the routes with Switch if you do not want to match multiple routes.

<BrowserRouter>
  <Switch>
    <Route exact path="/" component={ProfilesIndex} />
    <Route exact path="/profiles" component={ProfilesIndex} />
    <Route exact path="/profiles/new" component={ProfileEditor} />
    <Route exact path="/profiles/:id" component={ProfileEditor} />
  </Switch>
</BrowserRouter>

Upvotes: 14

Related Questions