Error encountered: Exceeded maximum update depth in Material UI Data Grid

Encountering an error or warning when inputting rows in the table that is causing the screen to freeze.

Warning: Maximum update depth exceeded. This issue can arise when a component triggers setState within useEffect, but useEffect doesn't have a dependency array or one of the dependencies changes constantly on each render.

For reference, you can find the code example here.

The error occurs after adding:

onSelectionChange={(newSelection) => {
                        select(newSelection.rows);
                    }}

in the DataGrid component.

Answer №1

Instead of utilizing useState, consider using useRef. Unlike useState, useRef does not trigger a re-render of the component as it operates independently from the component lifecycle, thus resolving the issue at hand.

You can manipulate and retrieve the selected rows through useRef.current.

I have made modifications to your sample component by implementing useRef instead of useState below and provided a functional demo. Please note that in the example, the selected rows are displayed in the console log.

import React from "react";
import "./styles.css";
import { ColDef, DataGrid, RowsProp } from "@material-ui/data-grid";

export default function App() {
  const selectedRows = React.useRef([]);

  const onSelect = (event) => {
    selectedRows.current = event.rows;
    console.log(selectedRows.current);
  };

  const rows: RowsProp = [
    {
      id: 0,
      name: "LuluBox_v4.8.8_apkpure.com.apk",
      type: "application/vnd.android.package-archive",
      lastModifiedDate: "2020-10-20T00:27:43.669Z",
      size: "13805 kB",
      file: { path: "LuluBox_v4.8.8_apkpure.com.apk" }
    },
    {
      id: 1,
      name: "LuluBox_v4.8.8_apkpure.com.apk",
      type: "application/vnd.android.package-archive",
      lastModifiedDate: "2020-10-20T00:27:43.669Z",
      size: "13805 kB",
      file: { path: "LuluBox_v4.8.8_apkpure.com.apk" }
    }
  ];
  const columns: ColDef[] = [
    { field: "id", hide: true },
    { field: "name", headerName: "Name", width: 400 },
    { field: "size", headerName: "Size", width: 250 },
    { field: "lastModifiedDate", headerName: "lastModifiedDate", width: 400 }
  ];
  return (
    <DataGrid
      rows={rows}
      columns={columns}
      pageSize={8}
      autoHeight
      checkboxSelection
      hideFooter
      onSelectionChange={onSelect}
    />
  );
}

Answer №2

To solve the problem, it's important to check the difference between the previous state and the updated value received from the setSelectionChange method prior to using setState.

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

Guide on implementing a Pug for loop using AJAX

For my school project, I am developing a web application similar to Tinder using Node.js, Express, and Pug. The main goal of the project is to provide potential matches to users based on either their proximity or common interests with the current user. Whe ...

stop the menu component from triggering a re-render

I am facing an issue where the menu opens and closes briefly when I refresh the page. I want to find a way to prevent this re-rendering process. Every time I refresh, my console.log shows: false 'open' navigation.jsx:23 item navigation.jsx: ...

Guide on how to dynamically display a specific field in Material Table React

Hey there! I'm currently working with Material Table in React and I have a question. I want to generate a label tag for every cell, so I tried the following: <Table onChangePage={handleChangePage} page={p ...

Adjusting image dimensions dynamically using JavaScript based on screen size

My bootstrap setup seems to be causing issues when using the @media (min-height: 1000px) rule as the image class does not respond as expected. I am looking to implement a JavaScript solution that will automatically resize images once the screen height exc ...

Unable to locate FFmpeg on the root server for Discord JS v13

After setting up my DiscordJS Bot on a new rootserver, I transferred all the files and launched the bot. Everything seemed to be working fine until I tried to run a command that involved the bot joining a voice channel and playing audio. At this point, an ...

Using Vue.js - Incorporate filtering functionality within the v-for loop

I've successfully implemented a Vue filter that restricts the length of an array to n elements. It functions perfectly when used like this: {{ array | limitArray(2) }} Now, I'm attempting to utilize it within a v-for loop as follows: <li v- ...

Use Angular to change the style of multiple element groups at the same time when hovering

When hovering over an element with a common attribute, such as a class name, I want to change the style of all elements that share that attribute. Achieving this effect is simple with jQuery: $(function() { $('.bookId4').hover( function(){ ...

Issue encountered when trying to insert an array in JavaScript into MongoDB using Mongoose

I am currently learning about node.js and mongodb. I attempted to insert a JavaScript array variable into mongodb using mongoose, but encountered an error. Upon running this code, I received the following error message: ValidationError: CastError: Cast t ...

Sending data from an Angular application using AJAX to FormSpree.io

Currently, I am using a jQuery script to send ajax requests to for static form submission. The documentation provided by FormSpree suggests the following approach: $.ajax({ url: "//formspree.io/<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

Can you please explain to me how to target a specific element by its ID in the DOM and then move on to the next element with the same ID using jQuery

During the event handling process, a scenario arises where two div elements end up having identical IDs within the DOM structure. While using JQuery, my objective is to specifically target the second occurrence of the div with the aforementioned ID in the ...

Guide on implementing retry functionality in JavaScript/Ajax

I am starting out with Javascript and Ajax, and I need to implement a retry mechanism that tries 3 times if the ajax response is not 200. Ajax Function - function fireAndForget(strURL) { log("will attempt to invoke... [ " + strURL + " ]"); var x ...

Navigating horizontally to find a particular element

I developed a unique Angular component resembling a tree structure. The design includes multiple branches and nodes in alternating colors, with the selected node marked by a blue dot. https://i.stack.imgur.com/fChWu.png Key features to note: The tree&ap ...

Why is my Laravel Vue CRUD not automatically updating the posts section with new data?

Hey there, I've been working on a project using Laravel 5.6 with Vue.js for CRUD functionality. I'm trying to display the posts I've just added in the posts section without having to reload the entire page. However, my current code is only s ...

Combining two JSON objects in JavaScript is simple when their IDs correspond to each other in both objects

I have a query related to merging two different objects from the database, both in JSON format. These two objects share two key/value pairs: IRBId = ... and id = ..., which can be seen in the examples below: OBJ 1 { "data":{ "IRBs":{ "n ...

Guide on implementing a filter on an image using P5 in a React application

Seeking clarity on a specific issue, I'm using a react-P5-wrapper to create my P5 canvas in React, and I want to apply a filter to an image. Typically, in P5, this would be done with image.filter(GRAY). However, when P5 is an instance in React, I can& ...

Having trouble getting a local npm installation to work from a specific file path?

After following the instructions from this helpful link to install an npm package through a file path, I encountered an error when attempting to use it: Cannot find module '<module_name>' or its corresponding type declaration Are there an ...

How can I unselect a radio button by double clicking on it?

I am in need of a specific feature: When a user clicks on a radio button that is already checked, I want it to become unchecked. I've attempted to implement this code but unfortunately, it has not been successful. $(document).on('mouseup' ...

Exploring the world of JSON manipulation in JavaScript

I've been experimenting with JSON recently and came across something I don't quite understand. Here is an example of some code I used: var str = "{'name':'vvv'}"; var cjson = eval ("(" + str + ")"); alert( ...

What does the client perceive or not perceive? Node.js, JavaScript, MySQL

For a university project, I am tasked with creating a web application that is compatible with both desktop browsers and mobile devices. The technologies I will be using include HTML, CSS, JavaScript, Node.js, and MySQL. I have recently familiarized myself ...

Automated method for triggering button clicks on a webpage using JavaScript with a tailored combination of unique tag and class name

Currently, I am exploring methods to automatically trigger a button click on a webpage with a specific tag and class. My approach involves using Tampermonkey (Javascript userscripts) to accomplish this task. Referencing the image of the CSS/HTML elements r ...