DEV Community

Marco Streng
Marco Streng

Posted on

Handle 'componentWillReceiveProps' deprecation warning

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)
  })
}
Enter fullscreen mode Exit fullscreen mode

with Hooks

const doSomething = (items) => {
  // some code to sort items ...
  return items
}

const [items, setItems] = useState(doSomething(props.items))

useEffect(() => {
  setItems(defaultSorting(items))
}, [items])
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
wolverineks profile image
Kevin Sullivan

Any downsides to putting this directly in the render?

...
return props.items.map(doSomething).map(...)
...
Collapse
 
marcostreng profile image
Marco Streng

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.

Collapse
 
pavankmv profile image
pavankmv

componentWillReceiveProps is still working in React v17.0.2. Is my observation correct? Please confirm