Skip to content

Instantly share code, notes, and snippets.

@cr0ybot
Last active August 1, 2023 13:27
Show Gist options
  • Save cr0ybot/fb6a251ac57e6eac469feee208d0d622 to your computer and use it in GitHub Desktop.
Save cr0ybot/fb6a251ac57e6eac469feee208d0d622 to your computer and use it in GitHub Desktop.
Expo Screen Brightness Hook (with React Navigation)
/**
* Screen brightness utility.
*/
import { useIsFocused } from "@react-navigation/core";
import * as Brightness from "expo-brightness";
import { useEffect, useState } from "react";
import { Platform } from "react-native";
/**
* Set screen to max brightness when component is mounted and React Navigation screen is focused.
*
* NOTE: Can no longer use the system brightness methods on Android, but that
* means permissions don't need to be requested: https://github.com/expo/expo/issues/22024
*/
export function useMaxBrightness(disabled?: boolean = false) {
const [originalBrightness, setOriginalBrightness] = useState<number | null>(
null
);
const isFocused = useIsFocused();
const maxBrightness = async () => {
if (originalBrightness !== null) return;
console.log("Setting brightness to max...");
// Save original brightness.
const currentBrightness = await Brightness.getBrightnessAsync();
setOriginalBrightness(currentBrightness);
// Set brightness to max.
await Brightness.setBrightnessAsync(1);
};
const resetBrightness = async () => {
if (originalBrightness === null) return;
console.log("Resetting brightness to original value...");
if (Platform.OS === "android") {
Brightness.restoreSystemBrightnessAsync();
} else {
Brightness.setBrightnessAsync(originalBrightness);
}
setOriginalBrightness(null);
};
useEffect(() => {
if (disabled) {
if (originalBrightness !== null) resetBrightness();
return;
}
if (isFocused) {
maxBrightness();
} else {
resetBrightness();
}
// Cleanup resets brightness to original value when component is unmounted.
return () => {
resetBrightness();
};
}, [disabled, isFocused]);
}
export default useMaxBrightness;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment