React Custom Hooks (useMediaPermission)
Tags: react, reactjsdevelopment, reacthooks, customhooks
Published: 2023-10-18 09:05:29

## INTRO 🔊
Hello World! 👋
Today's custom hook is `useMediaPermission`🔥. This post will discuss how to detect media permissions like the `camera` and `microphone` of any application.

## USAGE 🔊
While handling media applications like chat and live stream. We have to be aware of whether the user is given camera and microphone permissions or not and have to track whether the user denied or rejected the permissions while using the application. For that purpose, we are creating one custom hook.

> 📌`Note`: This hook is mainly focussing on camera and microphone permissions only, not other permissions like geolocation, notification, accelerometer etc...

## HOOK 1

```jsx
import { useEffect } from "react";

export const useMediaPermission = (callback, constraints) => {
  const getPermission = (type) => {
    try {
      navigator.permissions
        .query({ name: type })
        .then((res) => {
          callback({
            name: res.name,
            state: res.state,
          });
          res.onchange = () => {
            callback({
              name: res.name,
              state: res.state,
            });
          };
        })
        .catch((error) => {
          console.log(error.message);
        });
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    if (constraints.length) {
      constraints.map((item) => getPermission(item));
    }
  }, [navigator.permissions]);
};

```

## USE CASE
```jsx
import React from "react";
import { useMediaPermission } from "./useMediaPermission";

function Inex() {
  const callback = (data) => {
    console.log(data);
  };
  useMediaPermission(callback, ["camera","microphone"]);
  return <div>Inex</div>;
}

export default Inex;

```

> 📌`Note`: `navigator.permissions.query` can't detect camera and microphone permissions in Firefox and Safari. It only supports the browsers Chrome and Edge. 
For more information visit this [link](https://github.com/expo/expo/issues/19485)
For that purpose we have created another hook

## HOOK 2
```js
import { useEffect } from "react";

export const useUserMediaPermission = (callback, constraints) => {
  const getPermission = (item) => {
    try {
      navigator.mediaDevices
        .getUserMedia({ [item]: true })
        .then((res) =>
          callback({
            name: item,
            state: res.active,
          })
        )
        .catch((error) =>
          callback({
            name: item,
            state: error.message,
          })
        );
    } catch (error) {
      callback({
        name: item,
        state: error.message,
      });
    }
  };
  useEffect(() => {
    if (constraints.length) {
      constraints.map((item) => getPermission(item));
    }
  }, []);
};
```

## USE CASE
```jsx
import React from "react";
import { useUserMediaPermission } from "./useUserMediaPermissoin";

function Inex() {
  const callback = (data) => {
    console.log(data);
  };
  useUserMediaPermissio(callback, ["audio", "video"]);
  return <div>Inex</div>;
}

export default Inex;

```

## DIFFERENCE BETWEEN HOOK 1 & 2 (LIMITATIONS)

- hook 2 will support all browsers but hook 1 will support only Chrome and Edge.
- If we change the permissions while using the application, hook 1 returns a callback with the latest permission status (whether it accepts or denied/prompted) but this feature won't work in hook 2.
- If we want to know only the initial status of media permissions, it's better to use hook 2.
- If we want to know the status of media permissions every time they change while using the application, it's better to user hook 1 (but this works only in Chrome and Edge)
- Recently I found one NPM package named [mic-check](https://www.npmjs.com/package/mic-check/v/1.1.0). This one is also very helpful to detect the media permissions but unfortunately, this package also detects the permissions only on page load, not every time changes the permissions while using the app.

I hope you people understand the `useMediaPermission` hook. We will meet with another hook in another post.

Peace 🙂