Search code examples
reactjscreate-react-apphookrouter

Using hookrouter with create-react-app fails to update the view on navigation change


I am attempting to get the most basic example of hookrouter (an alternative routing library to react-router-dom) working and cannot get the page to change. The URL address will change to /about when I click on the /about link but the UI doesn't update. I am using it with a brand new create-react-app project. I tried the same project on StackBlitz and noticed that after installing hookrouter it said there was a package/dependency missing for the 'url' library....which is interesting because the url package isn't a dependency of hookrouter. But the second I installed the url package on StackBlitz.io, the links worked and the UI updated appropriately when the url changed. I tried installing the url library on my local create-react-app project and it did not fix the situation. So I am not sure if there is a missing dependency, but I can see the useRoutes hook actually loading a change when the URL changes but for whatever reason the UI will not update. Here is my code for my App.js file.

import { A, useRoutes } from 'hookrouter';
import React from 'react';
import './App.css';
import { AboutPage } from './pages/AboutPage';
import { HomePage } from './pages/HomePage';

const routes = {
  '/': () => <HomePage />,
  '/about': () => <AboutPage />
}

function App() {
  const routeResult = useRoutes(routes);

  return (
    <div className="App">
      <A href="/">Home</A>
      <A href="/about">About</A>
      <header className="App-header">
        {routeResult}
      </header>
    </div>
  );
}

export default App;

Solution

  • It seems that hookrouter doesn't work with Strict Mode that comes enabled by default in the latest versions of CRA. (same I guess with StackBlitz and codesandbox)

    You'll need to just remove the <React.StrictMode> component from your index.js

    <React.StrictMode>
      <App />
    </React.StrictMode>
    

    codesandbox emaple

    With that said, Unless you have really simple App, I encourage you to use react-router-dom as this package is relatively new and you may have more unusual bugs.