Why do I need prevProps with prevState in componentDidUpdate()?
The first parameter in componentDidUpdate
is prevProps
. The second parameter is prevState
. The documentation clearly states that:
componentDidUpdate(prevProps, prevState, snapshot)
This
componentDidUpdate(prevState) {...}
is not a correct signature for the hook. Even though the first parameter was called prevState
, it contains previous props.
It's possible to alternate function parameters based on its arity but this isn't implemented in React and considered a bad practice in general because this leads to more complex signatures.
To not cause linter warnings, unused parameters can be underscored by convention:
componentDidUpdate(_prevProps, prevState) {...}
It doesn't matter if you are using prevProps
in your function or not, it has to be included, since the arguments order in functions does matter.
componentDidUpdate(prevProps, prevState)
If you'd omit the prevProps
argument, the prevState
(even tho the name would say clearly that it's previous version of state) it would stand for the previous version of props.
It's just a blank. You can use either an underscore, to tell others (or just yourself) that it's not used in that function.
componentDidUpdate(_, prevState)