How To Get Previous State in React

How to customize a usePrevious hook to implement it

Zachary Lee
Level Up Coding
Published in
2 min readSep 4, 2022

--

Photo by Tetiana SHYSHKINA on Unsplash

The Hooks introduced by React 16.8.x brought us a new development experience but also got some coding troubles. A common logic in our class components is to compare the front and rear props through the life cycle method to handle some logic, so how do we do it in function components?

Let’s start with a similar React.memo, which has a similar effect to the React.PureComponent class component, but it is actually a higher-order component. Its second parameter can get the previous props and the next props.

function MyComponent(props) {
/* render using props */
}
function areEqual(prevProps, nextProps) {
/*
return true if passing nextProps to render would return
the same result as passing prevProps to render,
otherwise return false
*/
}
export default React.memo(MyComponent, areEqual);

MyComponent does not re-render when areEqual returns true. And areEqual is optional, React's shallow comparison algorithm is used by default. For in-depth:

But what if I need to get the previous props in the component?

I define a usePrevious so that this logic can be reused in multiple components. Here is a use case:

import usePrevious from './usePrevious';function MyComponent(props) {
const { time } = props;
const previousTime = usePrevious(time);
if (time != previousTime) {
// Do something
}
}

Looking closely at usePrevious, it is actually a combination of the features of useRef and useEffect. Looks good and it helps avoid some boilerplate code.

Hooks are really popular, I have also explained some of my views on it, welcome to check it out!

Thanks for reading. If you like such stories and want to support me, please consider becoming a Medium member. It costs $5 per month and gives you unlimited access to Medium content. I’ll get a little commission if you sign up via my link.

Your support is very important to me — thank you.

--

--