DEV Community


componentWillReceiveProps / UNSAFE_componentWillReceiveProps in React Hooks world

Tomasz Kudlinski
Fullstack Engineer #react #typescript #node.js #react-native #redux #graphql #apollo
・1 min read

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.

Discussion (0)