Error while using useNavigate hook with react router
Hello guys,I am building a project while learning context api in react js.
I have put all my variables and functions in AppContext.jsx, so they can be accessed and manipulated by component according to the need.
But in some part of AppContext.jsx , I have used useNavigate hook (which must be used under Router, according to docs) is giving error that "useNavigate() may be used only in the context of a <Router> component ".
I don't know how to solve this error, please help me out in this.


4 Replies
afraid-scarletOP•2mo ago
Appcontext.jsx code

like-gold•2mo ago
Firstly, I wouldn't recommend using a context for a lot of these states. A lot of these things like data fetching and loading states are more global to your application, and providing them through your context will cause every single component that uses this context to re-render which will be horrible for performance. You should likely do your API requests either through tanstack query or through the route loaders and then accessing the state using route/query hooks.
TLDR; the reason you are having issues here is a bit of an XY problem. You want to access router hooks outside of the router because you are trying to define some API requests to trigger a navigation outside of the router, when really your API endpoints should not care about navigation.
---
With that out of the way, if you really want to keep the context, I would recommend just making a custom hook that uses that context to change page.
Then you can just get your
pageChangeHandler
by calling the hook
like-gold•2mo ago
If you would like a recommendation, I find that a context is the most powerful in two cases:
1. dependency injection
- https://tkdodo.eu/blog/react-query-and-react-context
- passing through values that are very unlikely to change such as the response from an API request to everything in an area of the application. For example,
isAuthenticated
could likely exist in a context because it's set once basically. Another example might be providing a serviceId to everything within a section of your application
2. Coordinating compound components state
- https://headlessui.com/react/tabs
- For example, if you have a tabs component, you might structure this so that you have a controller
which provides a context for the currently active tab, and then each tab might listen into this and behave as the active tab when the context matches their id. If you look at the headless UI tabs, the TabGroup
is likely a context that manages the active tab. Another example is an accordion list and a context that coordinates what the active accordion is.React Query and React Context
Can it make sense to combine React Query with React Context ? Yes, sometimes ...
Headless UI
Completely unstyled, fully accessible UI components, designed to integrate beautifully with Tailwind CSS.
afraid-scarletOP•2mo ago
Ok bro, now it's working thanks