I am working on updating react version to 18.2 from 16.8.6 in one of my projects. After doing the upgrade one of the major warnings that I got in console is regarding the deprecated lifecycle methods like componentWillReceiveProps
.
The warning given by react is Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run
npx react-codemod rename-unsafe-lifecycles in your project source folder.
.
But componentWillReceiveProps
is still working for me. Did I do something wrong while upgrading, or is it supposed to work?
2
Answers
The warning you’re seeing is expected. In React 16.3, the
componentWillReceiveProps
lifecycle method was deprecated and renamed toUNSAFE_componentWillReceiveProps
. This was done to highlight potential problems in an application, as this lifecycle method often leads to bugs and inconsistencies.However, to ease the transition and avoid breaking existing code, React continues to support the old names alongside the new
UNSAFE_
-prefixed names in non-strict mode. This is likely why your code withcomponentWillReceiveProps
is still working.In React 18.x, only the
UNSAFE_
name will work. So, it’s recommended to rename all deprecated lifecycles to their new names. You can do this manually, or by runningnpx react-codemod rename-unsafe-lifecycles
in your project source folder as suggested by the warning.So, you didn’t do anything wrong during the upgrade. The old lifecycle methods are supposed to still work in non-strict mode, but it’s recommended to move away from them to prepare for future versions of React.
I just bootstrapped a fresh React v18 project and used
componentWillReceiveProps
. It worked, and I got the same "In React 18.x, only the UNSAFE_ name will work…" text you did. So it’s still there, even in a fresh project.The documentation now says:
Apparently the warning text is somewhat out of date and the removal of the old name hasn’t been done yet.
That said, it’s probably best to at least rename the method in you code at this point (perhaps with the codemod they recommend), and ideally refactor to stop using it entirely.