Helo guys, i trying to use Refs and to give this.setState
inside 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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With