Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Refs woth setState giving Maximum update depth exceeded.

Helo guys, i trying to use Refs and to give this.setStateinside his but it give:

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.

How i'm doing:

ref = {
  (anchor) => this.setState({
    anchor
  })
} >

But when i use:

ref = {
  (anchor) => this.state.anchor = anchor
} >

it works..

And in other component, i use this.setState also and it works perfectly, someone why?

like image 894
ELD Avatar asked Aug 31 '18 18:08

ELD


2 Answers

ref is a special props in React. React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts. ref updates happen before componentDidMount or componentDidUpdate lifecycle hooks. So in the first example, when ref props callback function gets executed, before the mount you are changing the state using setState, so component again starts mounting due to state change. And now your are in Infinite call loop.

But in the second case, you are directly mutating the state which never should be done in React, and when you update the state by mutating directly the state it never kicks re rendering. So there is no Infinite call is happening. It mounted normally.

Note: ref is not a place to change the state. Refs provide a way to access DOM nodes or React elements created in the render method. As per the doc.

Hope that helps.

like image 67
Arup Rakshit Avatar answered Nov 16 '22 11:11

Arup Rakshit


1) refs must never be stored as a part of the component state. Just assign it to the component's member like this:

<div ref={ x => this.anchor = x } />

2) The component's state must never be modified directly. No this.state.x = something, use setState so React could detect the change and make the UI update.

3) setState() must not be called directly from the render() (which causes infinite rendering loop).

like image 25
gaperton Avatar answered Nov 16 '22 13:11

gaperton