DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Tomasz Kudlinski
Tomasz Kudlinski

Posted on

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.

Top comments (0)

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!