use-prev

This custom hook allows you to get previous value from the useState

Usage no npm install needed!

<script type="module">
  import usePrev from 'https://cdn.skypack.dev/use-prev';
</script>

README

What is this?

This custom hook allows you to get previous value from the useState

Installation vie package manager

  yarn add use-prev
  npm install use-prev

Usage


  import { useState } from "react";
  import usePrev from "use-prev";

  function MyComponent() {

    const [click, setClick] = useState(0);    
    const prevClick = usePrev(click);
    
    const increment = () =>
      setClick((_click) => _click + 1);

    return (
      <>
        <p>Current Click Value: {click}</p> // 1
        <p>Previous Click Value: {prevClick}</p> // 0
        <button onClick={increment}>
          Increment
        </button>
      </>
    )

  }