Homepage

How to get previous props in React Hooks

Getting the previous state of a property is a bit more convoluted in React Hooks vs. older class-based React. A quick guide to how to implement a custom usePrevious hook.

You can access the previous state of properties or state in React Hooks by implementing a custom hook - in this example I’ve called it usePrevious.

import { useEffect, useRef } fromreact’;

const usePrevious = (value) => {
  const ref = useRef();

  useEffect(() => {
    ref.current = value;
  });

  return ref.current;
};

export default usePrevious;

This uses the out-of-the-box useRef hook to compare any property that’s passed into the function against its previously stored value.

We can import this usePrevious hook into any component:

import usePrevious fromjavascript/utils/hooks/use-previous';

Then we can get any previous value for a prop or piece of state by passing it into our usePrevious hook:

const prevFetchFilters = usePrevious(fetchFilters);

In this example I want to get the previous state of the fetchFilters object, which contains a bunch of filters applied to a video listing, to see if any filters have been changed.

I can then comparing the previous state of the fetchFilters object against its current state, using the package deep-equal (https://www.npmjs.com/package/deep-equal), like:

!deepEqual(prevFetchFilters, fetchFilters);

What other people say

Other peoples’ opinions matter. I have worked with many people over the years and think it is important to share their experience of working with me.

  • React Development

    Tried and tested React application development. From super-fast single page applications to efficient large-scale corporate websites.

  • High-quality Templating

    Experienced approach to coding consistent and maintainable frontend templates and component libraries.

  • Accessibility Implementation

    Deep understanding of website accessibility, accessibility consultation, practical design, development, and testing experience.