Delay Rendering Of A React Component With Debounce – react-bouncer

react-bouncer is a component library that wraps components with a debounce, throttle, or any other delayed-rendering method, to stop them from re-rendering often when their props change.

How to use it:

1. Install & import.

# NPM
$ npm i @yaireo/react-bouncer
import bouncer from '@yaireo/react-bouncer'

2. Basic usages.

// simplified example for a component which gets rendered often due to props change
const Foo = ({x,y}) => `${x} ${y}`;
// uses 300ms `debounce` by default
const DebouncedFoo = bouncer(Foo)
DebouncedFoo.displayName = 'DebouncedFoo';

// use a `throttle` method instead of the default `debounce` (or use your own custom one)
const ThrottleddFoo = bouncer(Foo, 300, throttle)
DebouncedFoo.displayName = 'ThrottleddFoo';

// use them in another component which might render them often with different props
const App = () => {
  const [pos, setPos] = useState({x:0, y:0})
  // re-render on mouse move
  useEffect(() => {
    const onMouseMove = e => setPos({x: e.pageX, y: e.pageY})
    window.addEventListener('mousemove', onMouseMove)
    return () => window.removeEventListener('mousemove', onMouseMove)
  }, [])
  return <>
      <DebouncedFoo {...pos}/>
      <ThrottleddFoo {...pos}/>
  </>
}

Preview:

Delay Rendering Of A React Component With Debounce

Download Details:

Author: yairEO

Live Demo: View The Demo

Download Link: Download The Source Code

Official Website: https://github.com/yairEO/react-bouncer

License: MIT

You Might Be Interested In:

Add Comment