Get User Device Screen Information using React Js Hook.
Hello Readers… In this article, we will learn how to create our own hook for react js. There is a large number of hooks available in React Js. But also some important features/hooks are still missing in this framework. Today we are going to develop our own hook. This hook can be used in React Js and Next Js.
Intro to the hook: This hook will work by adding an onResize EventListener to the browser window and help us to get User device info. Our hook will give us the following information.
- Is the user has a Mobile / Tablet / Desktop Device.
- The width and height of the user device.
React Hook
A Hook is a unique function that lets you “hook into” React features. For example, useState is a Hook that enables you to add React state to function components. We’ll learn other Hooks later. (Read More)
Let’s start and develop our react hook.
First, we need to create the template of our code which contains some important hooks that are already available in the react js. and then we will create the function and export it as default.
import { useState, useEffect, useCallback } from 'react' function GetDeviceInfo() { return <></> } export default GetDeviceInfo
Now our template is ready and it’s time to add some extra code.
- First, we add the resize event listener. To add the lister we use a special react hook called useEffect, which will help us to run code when this hook is initialized. As we all know an event listener function takes 2 parameters. The first is for the listener name and the second parameter should be a function.
- We also use useState hook to manage the state of our hook and useCallback hook.
- Now create a function handleResize which will handle our functionality when the event listener called.
- Don’t forget to return a function from useEffect which removes the event lister from the window. If you forget to remove the event listener then you will get a warning in your browser console when your component will unmount from the document.
- In this hook, we are setting a 576 pixels limit for the mobile screens, between 576 to 800 for the Tablet screen and above 800 for the Desktop screen.
- Now it’s time to return the state object from our component. (
return <></>) (return object)
import { useState, useEffect, useCallback } from 'react' function GetDeviceInfo() { // Change the value as per your config const SCREEN_SIZES = { MOBILE_WIDTH: 576, // For mobile devices TABLET_WIDTH: 800, // For tablet devices } const { MOBILE_WIDTH, TABLET_WIDTH } = SCREEN_SIZES const [object, setObject] = useState({ width: undefined, height: undefined, isMobile: false, isTablet: false, isDesktop: false }) const handleResize = useCallback(() => { const width = document.documentElement.clientWidth || window.innerWidth; const height = document.documentElement.clientHeight || window.innerHeight setObject({ width: width, height: height, isMobile: width <= MOBILE_WIDTH, isTablet: width > MOBILE_WIDTH && width <= TABLET_WIDTH, isDesktop: width > TABLET_WIDTH }) }, [MOBILE_WIDTH, TABLET_WIDTH]) useEffect(() => { window.addEventListener('resize', handleResize) handleResize() return () => { window.removeEventListener('resize', handleResize) } }, [handleResize]) return object } export default GetDeviceInfo
And now I am writing the code here which will help you to use this hook in your React Js/Next Js applications.
import GetDeviceInfo from './GetDeviceInfo function MyComponent() { const { isMobile, isTablet, isDesktop, width, height } = getDeviceInfo() return <> {isMobile && <span>You are using a Mobile device</span>} {isTablet && <span>You are using a Tablet device</span>} {isDesktop && <span>You are using a Desktop device</span>} <p>And your browser screen size is {width} x {height}</p> </> }
IMPORTANT: This hook will give you the live effect when you resize your screen. ❤️
It’s time to learn more about the useState, useEffect and useCallback hook.
useState(): It returns a stateful value, and a function to update it. During the initial render, the returned state (state
) is the same as the value passed as the first argument (initialState
). The setState
function is used to update the state. It accepts a new state value and enqueues a re-render of the component.
useEffect(): The function passed to useEffect()
will run after the render is committed to the screen. Think of effects as an escape hatch from React’s purely functional world into the imperative world. By default, effects run after every completed render, but you can choose to fire them only when certain values have changed.
useCallback(): It returns a memoized callback. Pass an inline callback and an array of dependencies. useCallback()
will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g. shouldComponentUpdate
).
All done from my side 😊. If you guys have still any doubts or suggestions please let me know in the comment section. I will be very happy.
Thank You…
1 thought on “Custom React Hook – Get Device Screen Information – Simple JavaScript Code”