How to implement a custom hook for handling screen orientation changes in React



Image not found!!


To implement a custom hook for handling screen orientation changes in React, you can utilize the window object and the resize event to detect changes in screen dimensions. Here's how you can achieve this:

javascript
import { useEffect, useState } from 'react'; const useScreenOrientation = () => { const [orientation, setOrientation] = useState(getOrientation()); useEffect(() => { const handleOrientationChange = () => { setOrientation(getOrientation()); }; window.addEventListener('resize', handleOrientationChange); return () => { window.removeEventListener('resize', handleOrientationChange); }; }, []); return orientation; }; const getOrientation = () => { if (window.innerHeight > window.innerWidth) { return 'portrait'; } else { return 'landscape'; } }; export default useScreenOrientation;

In this custom hook:

  • We define a useScreenOrientation hook that returns the current screen orientation.
  • Inside the hook, we initialize the orientation state with the result of the getOrientation function.
  • We set up an effect that listens for the resize event on the window object. When the window is resized, the handleOrientationChange function is called to update the orientation state.
  • We define the getOrientation function, which checks whether the window height is greater than its width. If so, it returns 'portrait'; otherwise, it returns 'landscape'.

You can use this custom hook in your components as follows:

javascript
import React from 'react'; import useScreenOrientation from './useScreenOrientation'; const MyComponent = () => { const orientation = useScreenOrientation(); return ( <div> <h1>Screen Orientation: {orientation}</h1> </div> ); }; export default MyComponent;

With this setup, your component will automatically update when the screen orientation changes, and it will display the current orientation ('portrait' or 'landscape').