Purpose of componentWillReceiveProps/getDerivedStateFromProps

67 views Asked by At

I'm just learning React and I've come across something I can't find explained anywhere.

In every book/blog that I've read about React components I've seen a statement along the lines that component props are immutable. The only way to change a component's properties is to re-create it. That appears to not be the case, though.

In reading "React in Action" and "React Quickly" I've run across references to componentWillReceiveProps along with an explanation that this method is to be used when props (not state) is to be changed. I've seen the documentation for this (and the newer getDerivedStateFromProps function).

The documentation for componentWillReceiveProps stated:

componentWillReceiveProps() is invoked before a mounted component receives new props. 

The documentation for getDerivedStateFromProps states:

This method exists for rare use cases where the state depends on changes in props over time. 

Neither of these explains how it is that immutable props can be received (and changed?) at any time during the life of a component.

So, what is really going on here? If props can't be changed what are these functions/methods for? Or, are the books/blogs mistaken and these really are not immutable after all?

1

There are 1 answers

4
ray On BEST ANSWER

A component can be re-rendered with new/updated/different props. Consider the following component:

function Parent () {
    const [count, setCount] = useState(0);

    setInterval(() => setCount(count + 1), 1000);

    return (
      <CounterDisplay count={count} />
    )
}

The CounterDisplay component will get re-rendered with a new count prop once every second(ish). CounterDisplay could implement componentWillReceiveProps if it needed to do something in response to the new prop before re-rendering.

In practice this is pretty rare in projects running recent versions of React. I haven't implemented a componentWillReceiveProps method in a React component in years.