Example of useWindowSize() Custom hook in React.js

Example of useWindowSize() Custom hook in React.js

The useWindowSize hook helps you track the size of the browser window. Here's how to set it up:

import { useState, useEffect } from 'react';

const useWindowSize = () => {
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  useEffect(() => {
    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    };

    // Add event listener for window resize
    window.addEventListener('resize', handleResize);

    // Cleanup function to remove event listener
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return windowSize;
};

export default useWindowSize;

Now, let's see how you can use this custom hook in a component:

import React from 'react';
import useWindowSize from './useWindowSize'; // Assuming you've placed the hook in a separate file

const MyComponent = () => {
  const { width, height } = useWindowSize();

  return (
    <div>
      <h1>useWindowSize Hook Example</h1>
      <p>Window Width: {width}</p>
      <p>Window Height: {height}</p>
    </div>
  );
};

export default MyComponent;

In this example:

  • We define the MyComponent functional component.

  • We use the useWindowSize hook to track the size of the browser window.

  • The hook returns an object containing the width and height of the window.

  • We render the width and height values in the component.

This hook is great for making components that change based on the browser window size. You can change the layout or content of your components depending on how much screen space there is.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!