-
Notifications
You must be signed in to change notification settings - Fork 47.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
16.4 broke getDerivedStateFromProps()
#12912
Comments
This was referenced May 26, 2018
Closed
You made a mistake in your code:
The right way is: static getDerivedStateFromProps(props, state) {
if (props.value !== state.value) {
return {
value: props.value
};
}
return null;
} |
Please refer to #12898 |
@DavidBadura true, corrected the code samples. the issue still persists though. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In your recent blog post you announced a "bugfix" for
getDerivedStateFromProps()
:But in reality it broke a real-world library.
Now
getDerivedStateFromProps()
gets called on every re-render.Suppose a component watches for a property change.
The recommended approach is to store the property value in
state
, likethis.state.value
.Then, a user changes the input value, so both
this.state.value
and the property must be updated:The timeline is:
this.props.value
andthis.state.value
areundefined
.onChange(event)
handler triggers and callsthis.setState({ value: ... })
.getDerivedStateFromProps()
is called in the new React 16.4.props.value
hasn't been updated yet, butstate.value
has, so theif
condition triggers becauseprops.value === undefined
andstate.value = ...
. Hencethis.state.value
gets reset by thisif
condition and becomesundefined
(which is already a bug) becauseprops
are the "single source of truth" as per the official React recommendations.this.props.onChange(...)
line executes which updatesthis.props.value
which in turn callsgetDerivedStateFromProps()
again.if
condition triggers again becauseprops.value === ...
andstate.value = undefined
and sothis.state.value
becomes...
again.In my case it actually breaks the phone number input component:
The design requirement is to let a user set
value
externally which in turn must update the country flag icon.It worked in React 16.3.
In React 16.4 though
getDerivedStateFromProps()
gets called on each internal state update resulting in the country flag being reset every time a user types a character (because an incomplete phone number can't be a source of a country flag, e.g. USA and Canada both start with+1
, not to mention the whole NANPA region).The text was updated successfully, but these errors were encountered: