As part of the implementation of async rendering in React, there are a few lifecycle methods which will be deprecated in React 17 (see React Blog). A common used one is componentWillReceiveProps
. In most cases it is used to handle the
props change of a component.
So what to do?
One solution is to use the static getDerivedStateFromProps
method. There is a great 'HowTo' dev.to Post from Larry Price.
Another solution is to use React Hooks, especially the useEffect()
Hook. This might be a nice solution if you have a small component and want to switch to a functional component within this change.
Here is a simple example. Imagine we are rendering a table component with a list of items. All items must initially run through the doSomething()
method.
previous code
doSomething (items) {
// some code to sort items ...
return items
}
state = {
items: this.props.items
}
componentWillReceiveProps (nextProps) {
this.setState({
items: doSomething(nextProps.items)
})
}
with Hooks
const doSomething = (items) => {
// some code to sort items ...
return items
}
const [items, setItems] = useState(doSomething(props.items))
useEffect(() => {
setItems(defaultSorting(items))
}, [items])
We can use the useEffect()
Hook which by default runs on every render. To avoid unnecessary calls, we use [items]
as the second parameter. So useEffect()
only runs when the property items
has changed.
Important notice
Before switching to getDerivedStateFromProps()
or useEffect()
you should check if you really need this property handling. Have a look at this official React Blogpost for common bugs and anti-pattern.
Sometimes we write some properties to the state even if we don't need to. If you for example need to sort a list which comes from a property, do it during the render and avoid writing it in the component state.
β
If you got any kind of feedback, suggestions or ideas - feel free to comment this blogpost!
Top comments (3)
Any downsides to putting this directly in the render?
If there is no need to write the
items
into the state this would of course be the best solution.useEffect()
gets relevant if you need the data in the state because it can be changed through user interactions for example.componentWillReceiveProps is still working in React v17.0.2. Is my observation correct? Please confirm