use-on-visible

1.0.8 • Public • Published

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

Readme

Keywords

Package Sidebar

Install

npm i use-on-visible

Weekly Downloads

8

Version

1.0.8

License

MIT

Unpacked Size

14.2 kB

Total Files

7

Last publish

Collaborators

  • timhaley94