JSPM

react-use-previous

1.0.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 233
  • Score
    100M100P100Q83622F
  • License MIT

React hook for remembering a previous value.

Package Exports

  • react-use-previous

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-use-previous) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

React - usePrevious

React hook for remembering a previous value.

Install

npm install --save react-use-previous

Usage

This hook is similar to the one mentioned in the docs, but it returns a ref instead of the actual value, so that you can use this anywhere, even if some functions are cached.

import {useState} from 'react';
import usePrevious from 'react-use-previous';

function useFoo () {

  const [value, setValue] = useState ( 0 );
  const prevValue = usePrevious ( value );

  useEffect ( () => {

    function update () {

      // This function is cached, since this useEffect has no dependencies and gets only executed when mounting and unmounting
      // But it can still access the previous value

      const nextValue = Math.random ();

      if ( nextValue !== prevValue.current ) setValue ( nextValue );

    }

    $(window).on ( 'resize', update );

    return () => $(window).off ( 'resize', update );

  }, [] );

  return value;

}

License

MIT © Fabio Spampinato