1.0.8 • Published 4 years ago

use-on-visible v1.0.8

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

use-on-visible

A React hook that fires a callback when an element becomes visible

NPM

Install

npm install --save use-on-visible

Summary

useOnVisible accepts a ref which points to an element, a callback which fires once each time the element becomes visible, and an array of dependecies, similar to what you would pass to useEffect. This dependecy list required to keep the hook performant and avoid infinite loops.

Usage

A simple example:

import React, { useRef } from 'react';
import useOnVisible from 'use-on-visible';

function Foo() {
  const ref = useRef(null);
  useOnVisible(ref, () => console.log('visible!'), []);

  return <p ref={ ref }>Hello, world!</p>;
}

A callback with dependencies:

import React, { useRef, useState } from 'react';
import useOnVisible from 'use-on-visible';

function Foo() {
  const ref = useRef();
  const [count, setCount] = useState(0);

  useOnVisible(
    ref,
    () => setCount(count + 1),
    [count, setCount],
  );

  return (
    <div>
      <p ref={ ref }>Hello, world!</p>
      <p>Count: { count }</p>
    </div>
  );
}

Live demo

timhaley94.github.io/use-on-visible/

License

MIT © timhaley94

1.0.8

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.3

4 years ago

1.0.0

4 years ago