use-prev-prop

A custom React Hook that maintains a previous value for a prop (or any other value).

MIT License

Downloads
242
Stars
16

@use-it/prev-prop

A custom React Hook that maintains a previous value for a prop (or any other value). Based on a tweet by Chris Achard.

Installation

$ npm i @use-it/prev-prop

or

$ yarn add @use-it/prev-prop

Usage

Here is a basic setup.

const previousProp = usePrevProp(prop);

Parameters

Here are the parameters that you can use.

Parameter Description
prop The current prop

Return

This hook returns the previous value of the prop. Initially, this value will be undefined.

Example

Let's look at some sample code. Here is a Count component that displays the count and the previous count.

import React from 'react';
import usePrevProp from '@use-it/prev-prop';

const Count = ({ count }) => {
  const prevCount = usePrevProp(count);

  return (
    <div>
      <div>Current Count: {count}</div>
      <div>Prev Count: {prevCount}</div>
    </div>
  );
};

export default Count;

License

MIT Licensed

Contributors ✨

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!

Package Rankings
Top 10.19% on Npmjs.org
Badges
Extracted from project README
npm version All Contributors