The infinite loop issue arises when the useEffect is utilizing the useNavigate hook

As I integrate the useNavigate hook within React to guide users to a specific page post-login, an unexpected infinite loop arises. Most sources online recommend utilizing the useNavigate hook inside a useEffect block; however, this method triggers a Warning: Maximum update depth exceeded issue. This warning occurs when a component invokes setState inside useEffect without either having a dependency array or if one of the dependencies changes on each render.

An intriguing observation is that the max depth warning only surfaces after the second login attempt. In simpler terms, everything functions correctly during the initial login session upon server and client startup, but subsequent logins trigger the annoying maximum depth exceeded warning.

I incorporate the useNavigate hook in two distinct files for user login and admin login, both examples are provided below.

To shed more light on why the problem occurs specifically from the second login onwards, it is independent of whether I log in as an admin or a regular user. For instance, if my first login is as an admin, the maximum depth exceeded warning pops up regardless of whether the next login is as a user or an admin. The same pattern applies if my initial login is as a user.

Here are the troubleshooting steps I have executed so far:

  • Eliminating navigate from the dependency arrays (resulting in the same warning)
  • Omitting the useEffect blocks entirely (which leads to new warnings advising me to place the useNavigate hook within a useEffect hook, causing the login functionality to break completely)
  • Doing away with the dependency array altogether (even this results in the same warning)

Error message encountered while logging in as a user:

react-dom.development.js:86 Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
    at Navigate (http://localhost:3000/static/js/bundle.js:42950:5)
    at Routes (http://localhost:3000/static/js/bundle.js:43067:5)
    at div
    at Router (http://localhost:3000/static/js/bundle.js:43000:15)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:41809:5)
    at App

Error message faced while logging in as an admin:

react-dom.development.js:86 Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
    at Navigate (http://localhost:3000/static/js/bundle.js:42950:5)
    at Routes (http://localhost:3000/static/js/bundle.js:43067:5)
    at div
    at Router (http://localhost:3000/static/js/bundle.js:43000:15)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:41809:5)
    at App

Login.jsx

import { useState, useEffect } from "react";
import axios from "axios";
import { Link, useNavigate} from "react-router-dom";

const Login = () => {
  const navigate = useNavigate();

  // Rest of the Login component code...
};

export default Login;

AdminLogin.jsx

import { useState, useEffect } from "react";
import axios from "axios";
import { Link, useNavigate} from "react-router-dom";

const AdminLogin = () => {
  const navigate = useNavigate();

  // Rest of the AdminLogin component code...
};

export default AdminLogin;

Additionally, here's Private.jsx (user home page) and Admin.jsx (admin home page), although I don't believe the issue lies within these files.

// Private component
// Code snippet for Private.jsx

// Admin component
// Code snippet for Admin.jsx

Answer №1

If you want to keep track of changes in your localStorage, you can implement the following solution:

const verifyStorageChanges = () => {
  if (localStorage.getItem("authToken")) {
      navigate("/home");
  }
}

useEffect(() => {
  window.addEventListener("storage", verifyStorageChanges);
  return () => {
    window.removeEventListener("storage", verifyStorageChanges)
  }
}, []);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When submitting an Asp net mvc Form, some fields may not be posted as expected

I'm facing an issue with my ASP.NET MVC application form. Some fields that should be posted are missing, and I can't figure out why. <form id="FormRegistroUsuario" action="/Account/AdminSecurityUserAccountAdd"> <fieldset> ...

Reaching out to the Edge: Enhancing the jQuery Slider Experience

Alright, I'm really excited about using this amazing slider. What I love most is the "free mode" feature that creates this stunning sliding effect. The size and number of slides are absolutely perfect for me. But there's just one small adjustment ...

Make the download window appear automatically when downloading a file

How can I use JavaScript/TypeScript to prompt the browser to open the download window? My goal is to give users the ability to rename the file and select the download folder, as most downloads are saved directly in the default location. This is how I curr ...

What is the best way to verify a user's login status in AngularJS using $routeChangeStart event?

I am new to AngularJS and I need help checking if my user is logged in or not using $routeChangeStart. Controller angular.module('crud') .controller('SigninCtrl', function ($scope,$location,User,$http) { $scope.si ...

Adjusting the color of a specific part of a text within a string using

I am trying to update the color of specific keywords within a post. For example: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tempor lacinia urna eget gravida. Quisque magna nulla, fermentum fermentum od #keyword1 #keyword2 #keyword3 ...

What is the solution for fixing an error that says "There is no 'style' property on the 'Element' type"?

I'm struggling to fix an error in my JavaScript code. I created a script to display a tab indicator when a tab is clicked, but I keep getting the error message: "Property 'style' doesn't exist on type 'Element'". The tabs them ...

Loading a local FBX file in Three.js without the need to upload it

When attempting to load files selected by users in an HTML input, I encountered a problem with the loader expecting a URL in Linux style. I have tried various methods such as using a blob as a URL object, providing raw data to the FBX loader, and even usin ...

Guide to loading a minified file in Angular 2 with Gulp Uglify for TypeScript Bundled File minimization

In my Angular 2 application, I have set the TypeScript compiler options to generate a single outFile named Scripts1.js along with Scripts1.js.map. Within my index.html file: <script src="Scripts/Script1.js"></script> <script> ...

Creating a Three-Row Table with Material-UI and React

I am looking to achieve a layout similar to the one shown in the image below: I want to construct a table with three rows, where the third row is positioned below the first and second rows, and the width of the third row is equal to the combined width of t ...

Dispatching $emit / $broadcast events from multiple areas of the code and capturing them in a single location

I have a practice of sending $emits (or $broadcasts) from various parts of the code and different controllers, but intercepting them all from one centralized place. While this approach seems to be functioning properly, I am unsure if it may be considered b ...

When Socket.emit is called, it outputs <span> elements within a well-structured message

Currently working on a small chat application using Node.js, Express.js, and Socket.IO. However, I'm encountering an issue with formatting. Instead of displaying the message content within <span> tags as intended, it is printing out the actual t ...

How can I convert a list of checkboxes, generated by ng-repeat, into multiple columns?

Here is the HTML code snippet: <div class="checkbox"> <label> <input type="checkbox" ng-model="selectedAll.value" ng-click="checkAll()" />Check All </label> </div> <div class="checkbox" ng-repeat="carType i ...

Unable to verify POST $http request using $httpBackend

Currently, I am in the process of writing unit tests to cover the http requests of my app. Using Jasmine and Karma, I have been following a tutorial on how to use $httpBackend from https://docs.angularjs.org/api/ngMock/service/. However, I encountered an e ...

cycle through several handlebars entities

Hey friends, I could really use your help right now. I'm attempting to iterate through these objects using handlebars. RowDataPacket { idUser: 1, username: 'xxxxxx', password: 'xxxxx', fullname: 'Julian Rincon'}, RowDat ...

What is the best way to include a class with Knockout JS?

After going through the basic Knockout tutorial and examining various examples, I decided to try it out myself on jsFiddle. However, I encountered some issues as my attempts did not quite work. The goal is simple - I just want to add the class open to a d ...

Testing an Angular factory that relies on dependencies using JasmineJS

I have a factory setup like this: angular.module("myServices") .factory("$service1", ["$rootScope", "$service2", function($rootScope, $service2){...})]; Now I'm attempting to test it, but simply injecting $service1 is resulting in an &ap ...

Reveal the CSRF token to the client located on a separate domain

Utilizing the module https://www.npmjs.com/package/csurf to safeguard my public routes from cross-site request forgery. Due to the server and client being on separate domains, a direct method of passing the generated token to the client is not feasible. I ...

Tips for customizing the background color and image of a toaster

Looking to modify the background color and image based on the else condition (toaster.error) success: function (data) { if (data.message != ""){ toastr.success(data.message); ...

Synchronization problem with Apollo Client cache between multiple instances in a Next.js application using React Apollo and managed with pm2

Currently, I am utilizing Next.js and React Apollo for my application. To ensure optimal performance, I have configured my application to run with pm2 in a clustered mode featuring two instances. However, I have encountered an issue where switching user pr ...

Encounter the "Error: Source 'cloudsTileLayer-RasterSource' not found" message while trying to integrate a weather tile layer into Azure Maps

I have been working on a React application that utilizes the React-Azure-Maps npm package. My current challenge involves creating a weather layer, which I believe shares similarities with the sample code provided for layers. The code snippet responsible f ...