DEV Community

Tomasz Kudlinski
Tomasz Kudlinski

Posted on

2 1

componentWillReceiveProps / UNSAFE_componentWillReceiveProps in React Hooks world

Probably you are also one of the React developers, who needs to, from time to time, refactor class based React component to React Hook (aka get rid off lifecycle methods). During this process you may encounter UNSAFE_componentWillReceiveProps function... very often it will look like:

Alt Text

In this case, we are only checking if propA value has changed. We can easily use useEffect during the refactoring to Hook:

Alt Text

Sometimes logic inside of UNSAFE_componentWillReceiveProps function will check the current and next value of the propA, like here:

Alt Text

To refactor it to Hook we need a way to store previous value of propA without rerendering the component:

Alt Text

In mentioned situation we can use useRef Hook and store previous value of the propA in it at the end of useEffect Hook.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay