Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-hook-use-window-width

dziksu73MITdeprecated2.0.1TypeScript support: included

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

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

react, hook, react-hook, utils, useWindowWidth, use-window-width, window, width

readme

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

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

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

return (

Window width: {width}
); };


## 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`

```typescript jsx
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