RangeError: The React application has surpassed the maximum stack size limit, causing an error to be thrown

Hey there, I could use a hand. I'm fairly new to React and attempting to develop an application for managing contacts by adding them to Local Storage and deleting them. Below is the code snippet from my App.js file:

import React, {useState, useEffect} from 'react'
import {uuid} from 'uuidv4'
import AddContact from './AddContact'
import ContactList from './ContactList'
import Header from './Header'

function App() {
  // Utilizing useState Hooks in React
  const LOCAL_STORAGE_KEY = 'contacts'
  const [contacts, setContacts] = useState([])

  const addContactHandler = (contact) => {
    console.log(contacts)
    setContacts([...contacts, {id: uuid(), ...contact}])
  }

  const removeContactHandler = (id) => {
    const newContactList = contacts.filter((contact) => {
      return contact.id !== id
    })
    setContacts(newContactList)
  }
  useEffect(() => {
    const retrieve_contact = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY))
    if (retrieve_contact) {
      setContacts(retrieve_contact)
    }
  }, [])

  useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts))
  }, [contacts])

  return (
    <div className="ui container">
      <Header />
      <AddContact addContactHandler={addContactHandler} />
      <ContactList contacts={contacts} getContactId={removeContactHandler} />
    </div>
  )
}

export default App

I encountered an error Uncaught RangeError: Maximum call stack size exceeded.

Any guidance on resolving this issue would be greatly appreciated. Thank you!

Answer №1

Caution! You've landed in an infinite loop by updating the react state within the useEffect hook.

useEffect(() => {
    localStorage.setItem(DATA_STORAGE_KEY, JSON.stringify(data))
}, [data])

In a nutshell, you've instructed the useEffect to execute whenever there is a change in the data variable. This results in it running repeatedly whenever data changes, which subsequently triggers another change in data, leading to an endless cycle of useEffect. To avoid this, consider modifying your storage operations within your event handlers when adding or removing data.

Check out this code sandbox demo for reference on how to resolve this issue.

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

Implementing an ES6 class in a next.js application: A step-by-step guide

Currently, I am in the process of developing a next.js application and am looking to extract the code that interacts with the database from the API. To achieve this, I have developed a class that serves as a manager: class UserManager { async findUser ...

Retrieve the width of an element once the browser has finalized its dimensions

I am facing an issue with centering a pop-up box perfectly within the window using CSS properties. The code for the pop-up box styling is as follows: #pop_up { position: fixed; display: inline-block; border: 2px solid green; box-shadow: 0p ...

Retrieving text from Node.js with the help of regular expressions

I need to extract testcase ids from a list of testcases with titles. Each title includes an id and a description. I want to extract only the id. Here are some examples: TC-ABC-98.1.010_1-Verify the layout credit page TC-RegPMP-1.1.001_2-Verify the [MangerD ...

Understanding the concept of a "class variable" in Typescript when referring to a variable that belongs to another class

When we declare a variable at the class level and assign it the type of another class, such as in the following code: let greeter: Greeter; //line 1 greeter = new Greeter("world"); What is contained within 'greeter' on line 1? ...

How to Style Your ASP.NET Website: Utilizing a Stylesheet with Visual Studio 2010

I am having trouble adding a stylesheet to the master page of my asp.net web form. I want to create an inline navigation menu at the top of the page, but I can't seem to get it working. I have created the stylesheet in the same way I would for an HTML ...

React does not accept objects as valid React children

Struggling to display data from my redux store in components. How can I resolve this issue? Error message: Error: Objects are not valid as a React child (found: object with keys {id, name, float, price, id_sub, subcategory, id_types, type, id_ext, ...

The client using socket.io is receiving events for "double plus one"

While experimenting with socketio, I encountered a bug that others are experiencing as well but I haven't been able to find a valid solution. This is the server-side code: const app = require('express')(); const server = require('http& ...

Choose the div without a class

I currently have several divs displayed on my website. <div class="slide bx-clone"></div> <div class="slide"></div> <div class="slide"></div> <div class="slide bx-clone"></div> <div class="slide bx-clone" ...

Using Bootstrap-select dropdown in PHP with GET method allows for easy inclusion of dropdown options in your web

Currently, I am working on developing a product page that includes a dropdown menu for selecting items and a button to add them to the cart. The products are being retrieved from a MySQL database and then looped through to generate product tables. The drop ...

Comparing Selenium and Watir for JavaScript Testing within a Rails environment

In our experience with Rails apps, we have found success using RSpec and Cucumber. While Webrat is effective for non-AJAX interactions, we are now gearing up to write tests for our Javascript. We have used Selenium support in Webrat before, but I am inter ...

The issue with Bootstrap 4 modal not closing persists when loading content using the .load() function

Having an issue with my Bootstrap 4 modal, as I'm loading the body content externally using .load(), but it's not closing when I click on the close buttons. Any help would be highly welcomed. JavaScript Code Used: if(status){ $('#cartMe ...

What might be causing the sudden shifts in element positions during TweenLite animation?

I have created a demo of my code in this JSFiddle and also included it below. The issue I am facing occurs in Google Chrome, so I would recommend using that browser to replicate and fix the bug. Please note that the code is a snippet from a larger project ...

Method for eliminating double quotes from a string bound in Angular

https://i.sstatic.net/fWF8M.png https://i.sstatic.net/fWF8M.png Check out this code snippet: var app = angular.module('umovie-app'); app.directive('renamable', function($sce) { return { scope: { model: '=model', ...

Managing text size in HTML email designs

How can I maintain consistent font sizes in HTML EMAILS? The fonts look great on the website, but in my email they appear small and close together. Check out Live Demo I've attached a screenshot of how the email appears to me. Any suggestions on h ...

Error encountered at /edit-menu/edit/: The 'Product' object does not contain the attribute 'is_valid'

I am attempting to extract all product names from the Product model, display them along with their prices on the screen, and enable users to modify the price of any item. Although I have managed to list them out and provide an input field for the price, I ...

Verify the role upon logging in

After downloading the Yeoman Angular Fullstack, I noticed that it already has the basic login configuration in place. The login code snippet looks like this: $scope.login = function(form) { $scope.submitted = true; if(form.$valid) { Auth.login({ ...

Attempting to incorporate a new CSS sub menu alongside the current one

Having trouble with menu styling, I'm new to this and trying to add a sub menu to an existing drop down menu. Check out my JSFiddle This is the CSS code: .menu_main { float: left; width: 60%; } #access .menu { list-style: none; font-weight: normal ...

Issue with Safari div not exhibiting proper overflow functionality

I'm looking to set up a webpage with a single sidebar and content area. Here's how I envision it: <div id="mainWrapper"> <!-- Sidebar --> <div id="sidebar"> <p>Sidebar</p> <p>Sidebar< ...

Converting Three.js objects into arrays

I am new to Three.js and I want to add my 'palmtree' object to an array. I believe my code is correct, but something seems off. Here is the snippet of my code: var objects = []; var mtlLoader = new THREE.MTLLoader(); mtlLoader.load("objects/pal ...

Vercel enables faster PAAPI transactions through Edge Caching

When working on a Nextjs site hosted on Vercel and making a call to Amazon's paapi, it's important to keep in mind the limitations imposed by Amazon on the number of transactions allowed per second and per day. The approach I'm taking involv ...