Search code examples
reactjsreact-router-dom

Mixing useNavigate with useHistory in React


In my current workplace, the project that I am supposed to work on has used useHistory up to now. I know that in newer versions it is usually better to use useNavigate. Would it be okay (non-breaking) to start using useNavigate inside of my new components without changing the older components to use useNavigate.

I am worried that the components will have unexpected bugs that are hard to track later on if I break the convention.


Solution

  • I know that in newer versions it is usually better to use useNavigate. Would it be okay (non-breaking) to start using useNavigate inside of my new components without changing the older components to use useNavigate.

    React-Router v5 doesn't export any useNavigate hook, and React-Router v6 hasn't any useHistory export, and you can't have react-router-dom@5 and react-router-dom@6 installed at the same time. You can however use the react-router-dom-v5-compat Backwards Compatibility Package to bridge this gap during the upgrade migration.

    The basic migration path would resemble the following:

    1. Ensure your project is on React 16.8 or higher

    2. Install the compatibility package

      Run npm install react-router-dom-v5-compat

    3. Render the compatibility router

      add compatibility router

    4. Incrementally upgrade what you want/need

      Replace history with navigate.

      replace hooks

    Of course react-router-dom-v5-compat is only meant and intended to be a temporary solution, you should plan to complete the upgrade to React-Router-DOM 6 as quickly as possible and remove the compatibility package.

    1. Uninstall compatibility package

      npm uninstall react-router-dom-v5-compat

    2. Uninstall react-router (v5) and history (if you have it)

      npm uninstall react-router history

    3. Install React-Router 6

      npm install react-router-dom@6

    4. Remove the CompatRouter and clean up the imports (i.e. all imports from react-router-dom)

      remove CompatRouter