Camera permission
- React Native course
- Advanced
- Lesson 8/83
- 5 min
Learn to ask for camera permission.
Camera permission
To use the camera you must ask the user for permission. The expo-camera package offers Camera.requestCameraPermissionsAsync. This function returns an object; if the status field is 'granted' the camera is usable.
You make the permission request inside useEffect and write the result into state. State starts as null (not asked), then becomes true or false. This pattern is the most robust way to ask for permission when the app opens. If permission is denied you show a warning text instead of the camera.
Permission state
You keep the permission result in state: const [hasPermission, setHasPermission] = React.useState(null). The initial value null means 'not asked yet'. Inside useEffect you request the permission and write the result with setHasPermission(permission.status === 'granted').
During render you check three states: if null show 'Waiting for permission', if false show 'Permission needed', if true show the camera. This three-way check gives the user meaningful feedback in every case. While state is null the camera is not rendered; this prevents possible errors.
Practice Request permission and write to state
Complete the empty useEffect. Call const permission = await Camera.requestCameraPermissionsAsync(); write the result with setHasPermission(permission.status === 'granted'). The second argument of useEffect should be [].
Starter code
import React from 'react';
import { Camera } from 'expo-camera';
export function useCameraPermission() {
const [hasPermission, setHasPermission] = React.useState(null);
React.useEffect(() => {
// request permission and write the result
}, []);
return hasPermission;
}Sample solution
(async () => {
const permission = await Camera.requestCameraPermissionsAsync();
setHasPermission(permission.status === 'granted');
})();Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the permission function
const permission = await Camera.____();
const permission = await Camera.requestCameraPermissionsAsync();
Explanation: requestCameraPermissionsAsync asks for permission.
2 Match each state value to its meaning
| Term | Meaning |
|---|---|
null |
Waiting for permission |
true |
Camera available |
false |
Permission denied |
'granted' |
status value |
3 What is shown when hasPermission is null?
if (hasPermission === null) { ... }- A blank screen
- The camera
- A 'waiting for permission' text Correct answer
- A crash error
Explanation: When null, a 'waiting for permission' text is shown.