I just dealt with this problem, so I'll add my solution as a supplement on other answers given.
The problem here is that useEffect
doesn't really work as you would want it to, since the call only gets triggered after the first render so there is an unwanted delay.
If you use some state manager like redux, chances are that you will get a flicker on the screen because of lingering state in the store.
What you really want is to use useLayoutEffect
since this gets triggered immediately.
So I wrote a small utility function that I put in the same directory as my router:
export const callApis = (fn, path) => {
useLayoutEffect(() => {
fn();
}, [path]);
};
Which I call from within the component HOC like this:
callApis(() => getTopicById({topicId}), path);
path
is the prop that gets passed in the match
object when using withRouter
.
I'm not really in favour of listening / unlistening manually on history. That's just imo.