React-Native community hooks

Thuong To
2 min readNov 10, 2023

--

In this reading, you’ll explore the code used in these community hooks so that you can understand them better.

Install

The first step is to ensure that you have installed the community hooks package using the following statement:

npm install @react-native-community/hooks

Once this package is installed, you can access all the community package hooks.

useDeviceOrientationHook

This hook can determine if the user’s mobile device is viewed in landscape or portrait mode. You can utilize this hook to determine the orientation if your app needs to support both modes.

First, you can import the hook from the react-native-community package. Then you can directly use the hook within your React component.

import { useDeviceOrientation } from '@react-native-community/hooks' 

const orientation = useDeviceOrientation()

console.log('is orientation portrait: ', orientation.portrait)
console.log('is orientation landscape: ', orientation.landscape)

The useDeviceOrientation hook returns the orientation object. The object has two values: portrait and landscape.

useAppState Hook

The useAppState hook is quite useful. This hook is used to determine the current app state. It can be active, background or inactive (iOS only). This determines when the user puts the app in a closed, background, inactive or active state.

This information is helpful to the developer to take specific necessary actions within the app, depending on whether the app is actively running or in the background. For example, specific applications like banking applications may log out the user after a particular time of inactivity or when the app is in the background.

useClipboard Hook

Observe the code below, which uses useClipboard to store text from the clipboard within the app:

import { useClipboard } from '@react-native-community/hooks' 

// Inside the component

const [data, setString] = useClipboard()

<Text>{data}</Text>

<Button title='Update Clipboard' onPress={() => setString('new clipboard data')}>Set Clipboard</Button>

In this reading, you learned about a few standard hooks from the React Native Community that you can use within your applications.

Make sure to visit the React Native Community page (the link can be found in the Additional Resources section) for more information about other hooks.

--

--

Thuong To
Thuong To

No responses yet