DEV Community

Giovanni García
Giovanni García

Posted on

Hooks

One of the rules for using hooks is that you must use a hook inside a functional component.
Wege have to create a function that renders a component and then inside that function we can use hooks.

No colocar información anidad dentro de u state
No objetos dentro de otro objeto (anidados), ya que no se re-renderizará por React, así está diseñado


Custom Hooks

Checks if the user's device has a rear facing camera

Technique: Use the browser's getUserMedia API to check if facingMode='"environment", which means a camera exists that faces away from the user.

import { useEffect, useState } from "react";

/** Returns true if the user's device has a rear-facing camera */
export default function useHasRearFacingCamera() {
  const [hasRearFacingCamera, setHasRearFacingCamera] = useState<boolean | null>(null);
  useEffect(() => {
    const detectRearCamera = async () => {
      try {
        const hasRearCamera = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: { exact: "environment" } },
        });
        if (hasRearCamera) {
          setHasRearFacingCamera(true);
        }
      } catch {
        setHasRearFacingCamera(false);
      }
    };
    detectRearCamera();
  }, []);
  return hasRearFacingCamera;
};
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)