DEV Community

Cover image for Custom Dimensions HOOK for your React projects.
Ande Caleb
Ande Caleb

Posted on • Edited on

Custom Dimensions HOOK for your React projects.

while working on a certain project, i needed to ensure that it was fully adapted to mobile, without any issue, and since i wanted to take 100% ownership of the application processes, i needed to in-my-own-way track certain changes per time, since this was key to the application.

I found several solutions online, most of which had its downside and i wasn't too impressed, so i decided it would be best to carve mine. Below is my code snippets that did the magic, which led me to building a custom-hook, i like the idea of Hooks(useState, useRef, useReducer, useContext++).. the simplicity in its implementation led me to utilizing its power in my best ability.

So, i went ahead to break my solution down as simple as possible in such a way as can be replicated to do solve other problems.

useWindowDimensions.jsx

import React, { useEffect, useState } from "react";

function getWindowDimensions() {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height
  };
}

export default function useWindowDimensions() {
  const [windowDimensions, setWindowDimensions] = useState(
    getWindowDimensions()
  );

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions());
    }

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return windowDimensions;
}
Enter fullscreen mode Exit fullscreen mode

*How you use it. in a custom component 'MyComponent' *

import React from 'react';
import useWindowDimensions from './hooks/useWindowDimensions';

const MyComponent = () => {
  ...... 
    const { width:w, height:h} = useWindowDimensions();
  ...... 
 return (
       <>
            <AnotherComponent width={w} height={h} />
       </>
  );
}

export default MyComponent

Enter fullscreen mode Exit fullscreen mode

i hope this was really helpful..
let me know what you guys think.

Top comments (0)