#Problem with multiple loading states and spinners
1 messages · Page 1 of 1 (latest)
Based on the information provided in the knowledge sources, I can offer some insights and suggestions regarding your issue with multiple loading states and spinners in NextJS.
The problem you're experiencing seems to be related to how NextJS handles loading states, especially with parallel routes and client components. Here are some key points and potential solutions:
-
Loading UI and Streaming: NextJS provides a special
loading.jsfile that works with React Suspense to create meaningful Loading UI. This allows you to show an instant loading state from the server while the content of a route segment loads. Loading UI and Streaming -
Parallel Routes and Loading: When using parallel routes, each route can have its own independent loading state. This allows for more granular control over loading UI for different parts of your application. Parallel Routes - Loading and Error UI
-
Client Components and Loading: When using client components, especially in layouts, you need to be cautious about how checks and data fetching are performed. The NextJS docs suggest doing checks close to your data source or the component that will be conditionally rendered, rather than in layouts. Layouts and Auth Checks
- Data Fetching Patterns: Be aware of parallel and sequential data fetching patterns. If you have nested components each fetching their own data, it can lead to sequential loading and multiple spinners. Consider using parallel data fetching where appropriate. Parallel and Sequential Data Fetching
To address your specific issue:
-
Consider moving your auth check to a more appropriate place, such as a higher-level component or a custom hook, rather than the root layout.
-
Use the
loading.jsfile convention for route segments to optimize loading behavior. -
Implement Suspense boundaries to control where and how loading states appear:
<Suspense fallback={<div>Loading...</div>}>
{/* Your component that fetches data */}
</Suspense>
-
Ensure that your React Query setup is optimized for server-side rendering and client-side navigation. You might want to review your caching strategy and how queries are invalidated.
-
Consider using NextJS's built-in data fetching methods like
getServerSidePropsorgetStaticPropsfor initial data loading, which can help manage loading states more effectively.
If these suggestions don't fully resolve your issue, you might be encountering a known issue with loading states in parallel routes. There have been reports of loading UI not working correctly with parallel routes in production builds. Loading and Streaming UI will not work with parallel routes