The power of custom hooks in React (responsive design example)

 By and large, custom snare is an incredible example to deal with particularity and organization in your application. you can compose a custom hooks for nearly everything!

Hooks are capacities that let you "guide into" React state and lifecycle highlights from work parts. Hooks don't work inside classes — they let you use React without classes. (We don't suggest revising your current components for the time being nevertheless you can begin utilizing Hooks in the new ones on the off chance that you'd like.)

How about we take responsive window dealing with for instance.. 

The most widely recognized methodology for responsive plan is CSS media inquiries, yet now and again, we will need to deal with it through JavaScript (restrictively render segments, execute some rationale when window size is changing to some point, and so forth) 

In the model underneath you will perceive how we can utilize React hook for that reason + create code and reuse/share it across an app(s). 

A few announcements 

Our custom Hook is called useResponsiveWindow and gets sizes as a discretionary item. 

Hook name show is a utilization prefix followed by a narrating, camel cased name (like useState, useRef, useContext, and so forth) 

A large portion of the applications utilize these normal sizes which announced as a default utilizing DEFAULT_SIZES, however go ahead and change or pass your own to the hook . 

DESKTOP_MIN size is likewise a standard least goal for a work area see (Again, not a taboo..). we will utilize it later. 

To begin with, we will need to save state for first, on load, width and tallness utilizing useState.
const DEFAULT_SIZES = {
  small: [1366, 768],
  medium: [1400, 900],
  large: [1920, 1080],
  mobile: [360, 640]
};
export enum ResolutionState {
  XS = "Extra Small",
  SMALL = "Small",
  MEDIUM = "Medium",
  LARGE = "Large"
}
const DESKTOP_MIN = [1280, 720];
const useResponsiveWindow = (sizes = DEFAULT_SIZES) => {
  const [width, setWidth] = useState(window.innerWidth);
  const [height, setHeight] = useState(window.innerHeight);
  const resizeTimer = useRef(null);
.........

Track window size and store it
Adding resize event listener (remove it on unmount) and execute handleWindowResize which will save the new values.

.....
  const handleWindowResize = useCallback((e) => {
    clearTimeout(resizeTimer.current);
    resizeTimer.current = setTimeout(() => {
      setWidth(e.target.innerWidth);
      setHeight(e.target.innerHeight);
    }, 200);
  }, [setWidth, setHeight, resizeTimer]);
  useEffect(() => {
    window.addEventListener('resize',handleWindowResize);
    return () => {
      window.removeEventListener('resize', handleWindowResize);
    };
  }, [handleWindowResize]);
.....

Useful insights
Now that we have width, height and resolution thresholds, we get some insights that we can use in our application.

.....
  const resolutionState = useCallback((type) => {
    const index = type === 'width' ? 0 : 1;
    const value = type === 'width' ? width : height;
    if(value >= sizes?.small[index] && value < sizes?.medium[index]) {
      return ResolutionState.SMALL;
    } else if(value >= sizes?.medium[index] && value < sizes?.large[index]) {
      return ResolutionState.MEDIUM;
    } else if(value >= sizes?.large[index]) {
      return ResolutionState.LARGE;
    } else {
      return ResolutionState.XS;
    }
  }, [width, height]);
  const widthState = resolutionState('width');
  const heightState = resolutionState('height');
  const isMobile = useMemo(() => sizes?.mobile && width <= sizes?.mobile[0] && height <= sizes?.mobile[1], [width, height]);
  const isDesktop = useMemo(() => width >= DESKTOP_MIN[0] && height >= DESKTOP_MIN[1], [width, height]);
.....

Consuming the hook

const SomeComponent= () => {
  const {
    width,
    height,
    isMobile,
    isDesktop,
    widthState,
    heightState
  } = useResponsiveWindow();
  useEffect(() => {
    console.log(`Width state now is: ${widthState}`);
    // do something here...
  }, [widthState]);
  return (
    <div>
      <p>{`${width} (${widthState}) x ${height} (${heightState})`}</p>
      {isMobile && <div>Mobile View</div>}
      {isDesktop && <div>Desktop View</div>}
    </div>
  );
};

You can view an example here and the source code here:

import React, { useEffect } from 'react';
import { render } from 'react-dom';
import useResponsiveWindow from './responsiveWindow.hook';
import './style.css';
const App = () => {
  const {
    width,
    height,
    isMobile,
    isDesktop,
    widthState,
    heightState
  } = useResponsiveWindow();
  useEffect(() => {
    console.log(`Width state now is: ${widthState}`);
  }, [widthState]);
  
  return (
    <div className="cube">
      <p>{`${width} (${widthState}) x ${height} (${heightState})`}</p>
      {isMobile && <div className="cube small-cube">Mobile View</div>}
      {isDesktop && <div className="cube small-cube">Desktop View</div>}
    </div>
  );
};
render(<App />, document.getElementById('root'));

#viastudy

Post a Comment

0 Comments