if you want to remove an article from website contact us from top.

    maximum update depth exceeded. this can happen when a component repeatedly calls setstate inside componentwillupdate or componentdidupdate. react limits the number of nested updates to prevent infinite loops.

    Mohammed

    Guys, does anyone know the answer?

    get maximum update depth exceeded. this can happen when a component repeatedly calls setstate inside componentwillupdate or componentdidupdate. react limits the number of nested updates to prevent infinite loops. from screen.

    javascript

    I am trying to toggle the state of a component in ReactJS but I get an error stating: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside

    ReactJS: Maximum update depth exceeded error

    Ask Question

    Asked 4 years, 7 months ago

    Modified 1 month ago

    Viewed 440k times 270

    I am trying to toggle the state of a component in ReactJS but I get an error stating:

    Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

    I don't see the infinite loop in my code, can anyone help?

    ReactJS component code:

    import React, { Component } from 'react';

    import styled from 'styled-components';

    class Item extends React.Component {

    constructor(props) {

    super(props);

    this.toggle= this.toggle.bind(this);

    this.state = { details: false } } toggle(){

    const currentState = this.state.details;

    this.setState({ details: !currentState });

    {this.props.config.server}{this.props.config.verbose}{this.props.config.type}PLACEHOLDER MORE INFO{

    } render() { return (

    Details}

    )} }

    export default Item;

    javascriptreactjsreact-native

    Share

    Improve this question

    edited Jul 19, 2019 at 9:12

    Awais Saifi 671 1 silver badge 8 8 bronze badges

    asked Jan 29, 2018 at 8:45

    Maja Okholm 3,0072 2 gold badges 10 10 silver badges 16 16 bronze badges 64

    Change this.toggle() to this.toggle or {()=> this.toggle()} –

    learner

    Jan 29, 2018 at 8:53

    14

    Another improvement, though unrelated to your issue: Turn toggle(){...} into toggle = () => {...} so you don't need to bind it! –

    Berry M.

    Jan 29, 2018 at 9:16

    1

    Thanks @learner. You helped me also. Would you kindly explain the reason behind your solution. What is the difference between those two ? –

    Shamim

    Apr 15, 2020 at 10:27

    3

    @Shamim It's the difference between calling an existing function, and passing the reference to a function. It's helpful to understand we are writing code to be displayed and triggered when the user does something, not code to be triggered as soon as the user loads the page. reactjs.org/docs/faq-functions.html –

    DisplayName May 7, 2020 at 8:42 Add a comment

    12 Answers

    385

    that because you calling toggle inside the render method which will cause to re-render and toggle will call again and re-rendering again and so on

    this line at your code

    {Details}

    you need to make onClick refer to this.toggle not calling it

    to fix the issue do this

    {Details}

    Share Improve this answer

    edited Jan 29, 2018 at 9:02

    answered Jan 29, 2018 at 8:49

    Ali Faris 16.4k10 10 gold badges 43 43 silver badges 66 66 bronze badges 16

    I am facing a similar situation, but I need to pass a parameter to toggle, how can this be accomplished? –

    Niveditha Karmegam

    Feb 23, 2018 at 5:02

    73

    @NivedithaKarmegam Do onClick={(param) => this.toggle(param)}. This will not fire immediatly (and rerender). This is a callback definition (arrow function). –

    fabpico

    Feb 23, 2018 at 9:28

    22

    @FabianPicone tried your method but when i console.log it shows that "param" was passed as the event, should actually do onClick={() => this.toggle(param)} –

    iWillGetBetter

    Jul 31, 2018 at 2:44

    7

    @iWillGetBetter Yes the first param in onClick is the click event. If you need an additional param you can pass it also onClick={(event) => this.toggle(event, myParam)}. –

    fabpico

    Jul 31, 2018 at 9:26

    1

    I have this function closeEditModal = () => this.setState({openEditModal: false}); How to call it in render? –

    Nux

    May 23, 2019 at 11:31

    Show 2 more comments

    42

    You should pass the event object when calling the function :

    { this.toggle(e)}>Details}

    If you don't need to handle onClick event you can also type :

    { this.toggle()}>Details}

    Now you can also add your parameters within the function.

    Share Improve this answer

    answered May 6, 2018 at 15:19

    Florent Philippe 4294 4 silver badges 2 2 bronze badges 4

    The event object is automatically sent if nothing is specified. Just include an input parameter in the function that is called. –

    Jeff Pinkston

    May 24, 2018 at 20:31

    {

    3

    this.toggle(whateverParameter)}>Details} does the trick for me –

    iWillGetBetter

    Jul 31, 2018 at 2:42

    1

    Downvoted because of the noise about the event object, which has nothing to do with it. –

    Stijn de Witt

    Aug 7, 2020 at 13:26

    Add a comment 42

    Forget about the react first:

    This is not related to react and let us understand the basic concepts of Java Script. For Example you have written following function in java script (name is A).

    स्रोत : stackoverflow.com

    Fix the "Maximum Update Depth Exceeded" Error in React

    React is an excellent framework, but it can have some tricky "gotchas." One of which is when you accidentally cause an infinite loop, often resulting in the cryptic "maximum update depth exceeded" error.

    TypeOfNaN

    Fix the "Maximum Update Depth Exceeded" Error in React

    Nick Scialli • April 13, 2021 • 🚀🚀 6 minute read

    React is an excellent framework, but it can have some tricky “gotchas.” One of which is when you accidentally cause an infinite render loop, often resulting in the cryptic “maximum update depth exceeded” error.

    Infinite Render Loop

    You likely have gotten yourself into an infinite render loop. Here I’ll discuss the most frequent causes and how to fix them.

    Cause 1: Calling a Function Rather Than Passing a Reference to It

    You can get yourself into an infinite render loop by accidentally calling a state setter function rather than passing a reference to it. Consider the following code:

    function App() {

    const [terms, setTerms] = useState(false);

    const acceptTerms = () => {

    <>

    setTerms(true); }; return (

    Accept the Terms

    ); }

    We’re immediately calling acceptTerms rather than passing a reference to a function to the change handler. This means that, when the component renders, we immediately call acceptTerms, causing the component to re-render, and then immmediately call acceptTerms, and so on. To get ourselves out of this bind, we need to pass a reference to acceptTerms rather than immediately calling it:

    function App() {

    const [terms, setTerms] = useState(false);

    const acceptTerms = () => {

    <>

    setTerms(true); }; return (

    Accept the Terms

    ); }

    Cause 2: An Effect that Updates a Variable in Its Own Dependency Array

    A nice feature of React is that it’s reactive. We can use the useEffect hook to take an action based on a variable being updated. However, this can backfire: if the useEffect hook updates a variable that triggers the effect to re-run, then it’s going to keep updating and re-running, causing an infinite loop. Let’s consider the following example:

    function App() {

    const [views, setViews] = useState(0);

    useEffect(() => {

    setViews(views + 1);

    }, [views]);

    return <>Some content;

    }

    In this case, the useEffect hook will run when views is updated. But when the hook runs, views then gets updated and, in turn, causes the effect to run yet again. This becomes an infinite loop.

    One way to prevent this from happening is to use a callback function in your state setter:

    setViews((v) => v + 1);

    This will allow you to safely remove the views variable from the dependency array.

    function App() {

    const [views, setViews] = useState(0);

    useEffect(() => {

    setViews((v) => v + 1);

    }, []);

    return <>Some content;

    }

    Now the effect will only run on initial render and won’t be run when views is updated.

    If you can’t clean up the dependency array

    There might be some reason you can’t clean up the dependency array. It’s not optimal, but you could add an additional variable to the mix that limits whether the effect is re-run. For example, you could create an isInitialRender stateful variable.

    function App() {

    const [views, setViews] = useState(0);

    const [isInitialRender, setIsInitialRender] = useState(true);

    useEffect(() => {

    if (isInitialRender) {

    setIsInitialRender(false);

    setViews(v + 1); }

    }, [views, isInitialRender]);

    return <>Some content;

    }

    The setViews function will now only be called when isInitialRender is true, meaning when the effect is re-run, the views variable will not be incremented and we won’t re-trigger the effect.

    Cause 3: Your Effect Depends On a Function That’s Declared Inside the Component

    The useEffect hook uses referential equality to determine if any variables changed in its dependency array. This means that, even if an object appears identical to another object, the effect could be re-triggered because the objects are actually different in memory.

    A good example of this is when an effect depends on a function that’s declared within the component itself. For example:

    function App() {

    const [views, setViews] = useState(0);

    const incrementViews = () => {

    setViews((v) => v + 1);

    }; useEffect(() => { incrementViews();

    }, [incrementViews]);

    return <>Some content;

    }

    Even though incrementViews appears like it will be the same function on every render, there’s actually a new function created in memory on each render.

    React has a couple solutions for this issue.

    Moving the Function Inside the Effect

    One quick solution is to move the function inside the useEffect hook.

    function App() {

    const [views, setViews] = useState(0);

    useEffect(() => {

    const incrementViews = () => {

    setViews((v) => v + 1);

    }; incrementViews(); }, []);

    return <>Some content;

    }

    We can see that now incrementViews is scoped inside the useEffect hook and a new function will only be created the one time the effect is run (on component mount). Since the function is inside the effect, we don’t even need to include it in the dependency array!

    The useCallback Hook

    The useCallback hook works a lot like the useEffect hook where the first argument is a function and the second argument is a dependency array. The difference is the useCallback hook will not create a new function unless one of the variables in its dependency array changes.

    स्रोत : typeofnan.dev

    Uncaught Error: Maximum update depth exceeded. React limits the number of nested updates to prevent infinite loops.

    react-dom.development.js:4379 Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly

    Uncaught Error: Maximum update depth exceeded. React limits the number of nested updates to prevent infinite loops.

    2022 6/15 React JavaScript エラー 2022年6月15日

    react-dom.development.js:4379 Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

    This error is caused by an infinite loop when setState is called during rendering in React.

    The contents of this error are as follows

    Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

    To fix this error, we need to change the code that is causing the infinite loop.

    In this article, I will show you how to solve this error and what causes it.

    目次

    The solution is to not call setState.

    The reason is that calling setState will cause it to be re-rendered.

    conclusion

    The solution is to not call setState.

    You can prevent infinite loops by not executing functions containing setState in event handlers such as the click event.

    Don’t put parentheses in the function by writing onClick={this.handleOpen} as shown in line 16.

    or

    You can eliminate the infinite loop by defining it as an arrow function in the event handler by writing onClick={() => this.handleOpen(false)} as shown in line 20.

    class OpenComponent extends React.Component {

    constructor(props) {

    super(props); this.state = { open: false, };

    this.handleOpen = this.handleOpen.bind(this);

    }

    handleOpen(is_open=true) {

    this.setState({ open: is_open);

    this.handleOpen(false)}>

    } render() { return ( OPEN CLOSE ) } }

    The reason is that calling setState will cause it to be re-rendered.

    The reason for the infinite loop is that the function containing the setState defined for the click event, etc. fires when rendering.

    The setState will re-render when called.

    Thanks to the setState() call, React knows the state has changed, and calls the render() method again to learn what should be on the screen.

    https://reactjs.org/docs/state-and-lifecycle.html

    The specific cycles that lead to infinite cycles are as follows

    Execute render() → execute this.handleOpen() → execute setState() → execute render() again → repeat

    In the following code, this.handleState() defined for the click event fires every time the component is rendered.

    class OpenComponent extends React.Component {

    constructor(props) {

    super(props); this.state = { open: false, };

    this.handleOpen = this.handleOpen.bind(this);

    }

    handleOpen(is_open=true) {

    this.setState({ open: is_open);

    // setStateを呼び出すので無限ループ // setStateを呼び出すので無限ループ

    } render() { return ( OPEN CLOSE ) } }

    conclusion

    Check if you are using setState in render, or if there are any functions that call setState.

    If you are calling setState, change it as follows.

    Pass the function name (no parentheses in the function name)Use the Arrow function

    The setState will no longer be called when rendering React, and the infinite loop error will be resolved.

    class OpenComponent extends React.Component {

    constructor(props) {

    super(props); this.state = { open: false, };

    this.handleOpen = this.handleOpen.bind(this);

    }

    handleOpen(is_open=true) {

    this.setState({ open: is_open);

    } render() { return (

    //

    //

    )

    }

    }

    Here is a good reference on how to pass functions to componentry.

    https://reactjs.org/docs/faq-functions.html

    React

    JavaScript

    エラー

    よかったらシェアしてね!

    Customers can order more than they have in stock on shopify.

    Controlling the Checkbox in Material UI with React Hook Form.

    関連記事

    Next.jsでPrismaを使ってデータベースを作る

    2022年5月14日

    next-seoを使ってNext.jsプロジェクトのSEOを管理する

    2022年4月1日

    react-beautiful-dndで順序をドラッグ&ドロップで入れ替える

    2022年3月23日

    स्रोत : omkz.net

    Do you want to see answer or more ?
    Mohammed 14 day ago
    4

    Guys, does anyone know the answer?

    Click For Answer