Skip to content

DeviceInfoProvider.jsx

Nikita Mogilevskii edited this page Feb 18, 2025 · 1 revision

The DeviceInfoProvider.jsx file provides device-specific information to the React application. It uses React Context API to share device info across components.

Code Breakdown

1. Imports

  • React, createContext, useContext, useState, useEffect: Core React utilities.

2. Context Creation

  • DeviceInfoContext: Context for sharing device information.
  • useDeviceInfo: Custom hook to access the context.

3. Device Info State

Manages the following device information:

  • ip: Public IP address.
  • deviceType: mobile or desktop.
  • orientation: portrait or landscape.
  • browserModel: Browser type (e.g., Chrome, Firefox).
  • operatingSystem: OS type (e.g., Windows, macOS, Linux).

4. IP Fetching

  • Fetches the IP address from https://api.ipify.org?format=json.
  • Handles errors gracefully if the fetch fails.

5. Device Detection

  • Uses navigator.userAgent to detect device type and browser.
  • Uses navigator.platform to identify the operating system.

6. Orientation Detection

  • Checks window dimensions to determine orientation.
  • Updates orientation on resize events.

Lifecycle Events

  • Mount: Fetches IP and sets initial device info.
  • Resize: Updates orientation on window resize.
  • Unmount: Cleans up resize event listener.

Usage

To use the DeviceInfoProvider:

import { useDeviceInfo } from './services/DeviceInfoProvider';

const deviceInfo = useDeviceInfo();
console.log(deviceInfo);

Clone this wiki locally