Protect route in React Router using HOC got dispatching infinity loop

Chai Phonbopit
Today I Learned ❤️Chai
2 min readDec 24, 2018

Today, I’ve picked my old project that created a half year ago, and want to implement new feature, so I start a project but I have a problem when using React Router to control authentication flow, that’s dispatching infinity loop 😱

😱Oh, infinity loop….

After I spend time to figure it out, I found a problem React Redux v6 that have breaking change about store and context

Also, there is a behavior change around dispatching actions in constructors / componentWillMount. Previously, dispatching in a parent component's constructor would cause its children to immediately use the updated state as they mounted, because each component read from the store individually. In version 6, all components read the same current store state value from context, which means the tree will be consistent and not have "tearing". This is an improvement overall, but there may be applications that relied on the existing behavior.

I got it.

because of my old code use react-router v5.0.1 and implement Private Route by using HOC like this:

PrivateRoute.js file

and define routing like this:

import PrivateRoute from './PrivateRoute'export default () => (
<Switch>
<Route path="/products" component={PrivateRoute(ProductList)} />
</Switch>
)

Its working when you use react-redux v5.0.1 but not working when using react-redux v6.0.0

I change the way to define private route to create component base instead of implement HOC by following this post

now my PrivateRoute.js change to

and define routing with Component to this:

import PrivateRoute from '../PrivateRoute'export default () => (
<Switch>
<PrivateRoute exact path="/products" component={ProductList} />
</Switch>
)

Now, its working again 🎉

--

--