I have some redux thunks that need to call history.push()
.
It first I was trying to avoid having to pass the history
object in the thunk call, so I did the following change in my code:
From this:
index.tsx
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<App/>
</BrowserRouter>
);
To this:
index.tsx
import { Router } from "react-router-dom";
import { history } from "./history";
ReactDOM.render(
<Router history={history}>
<App/>
</Router>
);
history.ts
import { createBrowserHistory } from "history";
export const history = createBrowserHistory();
But now that I've come to the SSR phase of my project, this has become a nightmare. Because I cannot call createBrowserHistory()
on my server code (NodeJS).
QUESTION
The pattern above is very comfortable to use both with redux thunks and some other helper functions that need to call history.push()
. I simpy have to import { history } from "@src/history";
from whatever file that needs it and use it directly.
But since this is conflicting with my SSR code, I'd like to know what is the best practice / recommended approach to this situation. Should I get the history
object from the components by using const history = useHistory()
and pass it to the thunks / functions that need it? Or is there a better approach?