Tel: (+44) 1482 234021 | info@wearesauce.io

React Native APIs you should know about

Something I overlooked when starting with React Native is the numerous available APIs for doing more than updating the ui and handling input, presses and gestures.

I wanted to make note of a handful of APIs that are likely to be useful when building applications with React Native. If you’ve been wondering how to save and load data, check if a device is online or offline, know if your app is in the background or active for performance reasons, using geolocation capabilities, vibrations, animations and a few more, then keep reading.

AsyncStorage

On the web we have the privilage of LocalStorage, however when building react native apps this isn’t the case. Instead, we have the AsyncStorage API which provides functionality for persisting data to the running device and reading it later.

Both AsyncStorage.getItem and AsyncStorage.setItem can be used to read and write values. One common use case in almost all of our apps is to store the users authentication token so that they are not forced to login next time the app is opened, AsyncStorage makes this really easy to do.

import React from "react";
    import { AsyncStorage, View, Text, TextInput } from "react-native";
    
    class StorageExample extends React.Component {
      state = { savedText: null };
    
      componentDidMount = async () => {
        const savedText = AsyncStorage.getItem("text");
    
        this.setState({ savedText });
      };
    
      handleTextChange = inputValue => {
        AsyncStorage.setItem("text", inputValue);
      };
    
      render() {
        return (
          <View>
            <TextInput
              value={this.state.savedText}
              onChangeText={this.handleTextChange}
            />
            <Text>{this.state.savedText}</Text>
          </View>
        );
      }
    }

AppState

With the AppState API we can keep track of whether our application is currently active, inactive or running in the background. Simply read from AppState.currentState to retrieve the current status of your application or listen to the change event.

import React from "react";
import { AppState, Text, View } from "react-native";

class ApplicationStatusHistory extends React.Component {
  state = {
    history: [AppState.currentState]
  };

  componentDidMount() {
    AppState.addEventListener("change", this.handleApplicationStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener("change", this.handleApplicationStateChange);
  }

  handleApplicationStateChange = status => {
    this.setState({
      history: [...this.state.history, status]
    });
  };

  render() {
    const statuses = this.state.history.map((status, index) => {
      return <Text key={index}>{status}</Text>;
    });

    return <View>{statuses}</View>;
  }
}

Net Info

If your app needs to work offline or at least show your users a helpful message as to why your app appears to broken when not connected, then NetInfo can be used.

Similar to AppState we can listen for the connectionChange event that will be dispatched as the device connects/disconnects between network connections.

import React from "react";
import { NetInfo, View, Text } from "react-native";

class ApplicationStatusHistory extends React.Component {
  state = { connected: false };

  componentDidMount() {
    NetInfo.addEventListener("connectionChange", this.handleConnectionChange);
  }

  componentWillUnmount() {
    NetInfo.removeEventListener(
      "connectionChange",
      this.handleConnectionChange
    );
  }

  handleConnectionChange = info => {
    const connected = info.type.match(/[wifi|cellular]/);

    this.setState({ connected });
  };

  render() {
    const statuses = this.state.history.map((status, index) => {
      return <Text key={index}>{status}</Text>;
    });

    return <View>{statuses}</View>;
  }
}

Vibration

The Vibration API gives us access to the devices motors if available. There are just two functions to remember, they are Vibration.vibrate and Vibration.cancel.

import { Vibration } from "react-native";

/**
 * Vibrate for a fixed period of time in ms.
 * Note: On iOS the length of the vibration can not be configured, roughly ~500ms will be used.
 */
Vibration.vibrate(1000);

/**
 * Vibrate using a pattern.
 * Android: Wait 250ms => Vibrate for 400ms => Wait 350ms => Vibrate for 800ms
 * iOS: Wait 250ms => Vibrate for ~500ms => Wait 400ms => Vibrate for ~500ms => Wait 350ms => ...
 */
Vibration.vibrate([250, 400, 350, 800]);

Dimensions

Whether you are creating a complicated layout or calculating a slick animation that should work on multiple display sizes, the Dimensions API is a simple and effective way of getting more information about the size of the screen your app is being rendered on. To get the space available we use Dimensions.get which returns an object containing a width and height key.

import { Dimensions } from "react-native";

const { width, height } = Dimensions.get("window");

console.log(`Hey, the area of your screen is ${width * height}`);