This package has been deprecated

Author message:

Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

react-hook-use-window-width
TypeScript icon, indicating that this package has built-in type declarations

2.0.1 • Public • Published

React hook: useWindowWidth

A simple hook for React to receive current window width using ResizeObserver for a better performance.

Requirements

A minimal requirements to use the package:

{
  "react": ">=16.8"
}

Installation

Use the package manager yarn or npm to install react-hook-use-window-width.

npm install react-hook-use-window-width

or

yarn add react-hook-use-window-width

Usage

import React from 'react';
import useWindowWidth from 'react-hook-use-window-width';

const MyComponnet: React.FC = () => {
  const width = useWindowWidth();

  return (
    <div>
      Window width: <strong>{width}</strong>
    </div>
  );
};

RAW implementation

If you don't want to use the package, and you only need a simple hook implementation you can just copy and paste the current implementation from /src/index.tsx

import { useCallback, useEffect, useRef, useState } from 'react';
import ResizeObserver from 'resize-observer-polyfill';

function useWindowWidth(): number {
  const isMounted = useRef<boolean>(true);
  const isSsr = typeof window === 'undefined';
  const [width, setWidth] = useState(isSsr ? 0 : window.innerWidth);

  const handleResize = useCallback(() => {
    if (isMounted.current) {
      setWidth(window.innerWidth);
    }
  }, [setWidth]);

  useEffect(() => {
    const observer = new ResizeObserver(handleResize);

    const element = window.document.querySelector('html');
    if(!element) return;
    observer.observe(element)

    return () => {
      isMounted.current = false;
      if(!element) return;
      observer.unobserve(element)
    };
  }, [handleResize]);

  return width;
}

export default useWindowWidth;

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

/react-hook-use-window-width/

    Package Sidebar

    Install

    npm i react-hook-use-window-width

    Weekly Downloads

    39

    Version

    2.0.1

    License

    MIT

    Unpacked Size

    14.3 kB

    Total Files

    12

    Last publish

    Collaborators

    • dziksu