Skip to content

timhaley94/use-on-visible

Repository files navigation

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