This content originally appeared on DEV Community and was authored by Senichi
One of the biggest driving forces behind React 17 is asynchronous rendering which aims to improve both the user and developer experience.
In React v16.3 the React team introduced few new lifecycles and deprecated some of the old ones.
Not due to security, these lifecycles will be more likely to have bugs in future versions of React, especially once async rendering is enabled.
To allow asynchronous rendering, there has to be a change in the component lifecycle and this involves deprecation of lifecycle methods which were introduced without async rendering in mind.
- componentWillMount → UNSAFE_componentWillMount
- componentWillReceiveProps → UNSAFE_componentWillReceiveProps
- componentWillUpdate → UNSAFE_componentWillUpdate
React 16.9 did not contain breaking changes, and the old names continue to work in this release. But you will now see a warning when using any of the old names. These warnings provide better alternatives to these lifecycle methods.
Easily Renaming UNSAFE Methods
To allow easy renaming for projects where one may not have adequate time to migrate to the recommended lifecycle methods, the React team recommended a script from codemod that automates this process.
cd your_project
npx react-codemod rename-unsafe-lifecycles
Conclusion
Asynchronous rendering is driving into version changes. To prevent bugs in future once async rendering is enabled.
To allow asynchronous rendering involves deprecation of lifecycle methods without async rendering in mind.
- componentWillMount → UNSAFE_componentWillMount
- componentWillReceiveProps → UNSAFE_componentWillReceiveProps
- componentWillUpdate → UNSAFE_componentWillUpdate
Now warnings provide better alternatives to these lifecycle methods.
Few new lifecycles was introduced too.
React Team has introduced one new lifecycle method named getDerivedStateFromProps()
to achieve the same functionality as UNSAFE_componentWillReceiveProps
will provide.
Replacement in Functional Component is no complete 1:1 but still we can achieve or use different Hooks at different scenarios to achieve the same result.
useMemo()
React hook specify all the props in an array that are dependent, it will run before everything whenever the props change.
Together getSnapshotBeforeUpdate(prevProps, prevState)
with componentDidUpdate
, this new lifecycle should cover all use cases for the legacy componentWillUpdate.
This content originally appeared on DEV Community and was authored by Senichi
Senichi | Sciencx (2021-09-20T23:01:20+00:00) unsafe react hooks. Retrieved from https://www.scien.cx/2021/09/20/unsafe-react-hooks/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.