how to set state when change viewport react

Hello developers! In this tutorial I have shared the details about “how to set state when change viewport react”. Okay, let’s move on to the tutorial.

how to set state when change viewport react

import React,  useLayoutEffect, useState  from 'react';

function useWindowSize() 
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => 
    function updateSize() 
      setSize([window.innerWidth, window.innerHeight]);
    
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  , []);
  return size;


function ShowWindowDimensions(props) 
  const [width, height] = useWindowSize();
  return <span>Window size: width x height</span>;

Conclusion

I hope this post helps you to know about “how to set state when change viewport react”. If you have any queries regarding this tutorial please let us know via the comment section. Share this tutorial with your friends and family via social networks.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coder Diksha. Here, I post about programming to help developers.

Share on:

Leave a Comment