Browse Source

More Sophie edits

main
Andrew Clark 7 years ago
parent
commit
0fe6a7905e
  1. 8
      content/blog/2018-05-23-react-v-16-4.md

8
content/blog/2018-05-23-react-v-16-4.md

@ -36,11 +36,9 @@ Huge thanks to [Philip Spiess](https://github.com/philipp-spiess) for contributi
### 1. Avoid Side Effects in `getDerivedStateFromProps`
Like the render method, `getDerivedStateFromProps` should be a pure function of props and state. You should move side-effectful code elsewhere. E.g. Flux dispatches typically belong inside the originating event handler. DOM mutations belong inside `componentDidMount` or `componentDidUpdate`.
Like the render method, `getDerivedStateFromProps` should be a pure function of props and state. Side effects in `getDerivedStateFromProps` were never supported, but since it now fires more often than it used to, the recent change may expose previously undiscovered bugs.
Side effects in `getDerivedStateFromProps` were already disallowed, but since it now fires more often than it used to, the recent change may expose previously undiscovered bugs.
You can read more about this in our recent post about [preparing for asynchronous rendering](/blog/2018/03/27/update-on-async-rendering.html).
Side effectful code should be moved to other methods: for example, Flux dispatches typically belong inside the originating event handler, and manual DOM mutations belong inside componentDidMount or componentDidUpdate. You can read more about this in our recent post about [preparing for asynchronous rendering](/blog/2018/03/27/update-on-async-rendering.html).
### 2. Compare Incoming Props to Previous Props When Computing Controlled Values
@ -78,7 +76,7 @@ static getDerivedStateFromProps(props, state) {
}
```
However, try to avoid mixing props and state in this way. Prefer to have one source of truth for any value, and [lift state up](/docs/lifting-state-up.html) if necessary to share it between multiple components.
However, try to avoid mixing props and state in this way -- it's rare that state needs to duplicate a value that exists in props and doing so can lead to subtle bugs. Prefer to have one source of truth for any value, and [lift state up](/docs/lifting-state-up.html) if necessary to share it between multiple components. Most uses of `getDerivedStateFromProps` (and its predecessor `componentWillReceiveProps`) can be fixed by moving the state management to a parent component.
Please remember that **most components do not need `getDerivedStateFromProps`**. It's not meant to serve as a one-to-one replacement for `componentWillReceiveProps`. We'll publish a follow-up post in the coming weeks with more recommendations on how to use (and not use) `getDerivedStateFromProps`.

Loading…
Cancel
Save