reactjs / react.dev

The React documentation website
https://react.dev/
Creative Commons Attribution 4.0 International
10.98k stars 7.5k forks source link

Don't recommend getDerivedStateFromProps as explicitly #954

Open gaearon opened 6 years ago

gaearon commented 6 years ago

https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html still contains a few recommendations to use getDerivedStateFromProps like:

As of version 16.3, the recommended way to update state in response to props changes is with the new static getDerivedStateFromProps lifecycle

We should figure out a way to dial them down or at least direct people to the newer blog post.

ghost commented 6 years ago

@gaearon That blog post on derived state, contains such important information I would advise to put it as a section under the official docs, and not as a blog post.

Also since we are at it, the blog post is generally well written, only the part about memoization is a little bit weak. Two points:

  1. The blog post mentions:

None of the implementations shown in this section will work if props.list is recreated each time the parent component renders. But in most cases, this setup is appropriate.

The blog post just contains above statement without giving further explanation why none of the examples would work if props.list is recreated. This doesn't seem evident to me either.

  1. This example:

class Example extends Component { state = { filterText: "", };

// // NOTE: this example is NOT the recommended approach. // See the examples below for our recommendations instead. //

static getDerivedStateFromProps(props, state) { // Re-run the filter whenever the list array or filter text change. // Note we need to store prevPropsList and prevFilterText to detect changes. if ( props.list !== state.prevPropsList || state.prevFilterText !== state.filterText ) { return { prevPropsList: props.list, prevFilterText: state.filterText, filteredList: props.list.filter(item => item.text.includes(state.filterText)) }; } return null; }

handleChange = event => { this.setState({ filterText: event.target.value }); };

render() { return (

    {this.state.filteredList.map(item =>
  • {item.text}
  • )}
);

} }


isn't complete in the sense that if filterText is changed by user in `input`, the items aren't re-filtered
with new filter value, isn't it?
Would not it be better to put a full, complete example instead? and reason about that?
nik72619c commented 5 years ago

is this issue open for work?