How to fix ‘Error: useRoutes() may be used only in the context of a component’ with React Router v6?

Sometimes, we want to fix ‘Error: useRoutes() may be used only in the context of a component’ with React Router v6.

In this article, we’ll look at how to fix ‘Error: useRoutes() may be used only in the context of a component’ with React Router v6.

How to fix ‘Error: useRoutes() may be used only in the context of a component’ with React Router v6?

To fix ‘Error: useRoutes() may be used only in the context of a component’ with React Router v6, we should call useRoutes in the component that’s use to render the route components.

For instance, we write

import React from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  useRoutes,
} from "react-router-dom";

const Component1 = () => {
  return <h1>foo</h1>;
};

const Component2 = () => {
  return <h1>bar</h1>;
};

const App = () => {
  const routes = useRoutes([
    { path: "/", element: <Component1 /> },
    { path: "component2", element: <Component2 /> },
    // ...
  ]);
  return routes;
};

const AppWrapper = () => {
  return (
    <Router>
      <App />
    </Router>
  );
};

export default AppWrapper;

to create the App component that calls the useRoutes hook with an array of route items.

Each item has the path that we go to to render the element.

And we render the routes by returning the routes object returned by useRoutes.

And then we put App inside Router to let us use React Router for navigation.

Conclusion

To fix ‘Error: useRoutes() may be used only in the context of a component’ with React Router v6, we should call useRoutes in the component that’s use to render the route components.