Mega Bundle SALE is ON! Get ALL of our amazing React Native codebases with 85% OFF discount ūüĒ•

Optional imports support has been added recently in React Native.This feature requires no external library and is relatively easy to implement even with its enormous advantage to the overall code quality of your code. The major use-case of this feature is backwards compatibility which we will look right into next.

Backwards Compatibility

This optional import helps us achieve some form of backwards compatibility especially since React Native core modules are being abstracted to be standalone dependencies. Ideally, this should let users on old versions of React Native¬†continue to use the version of AsyncStorage¬†that is exported from¬†react-native¬†or the react-native-community version if that’s not available.

import { AsyncStorage } from 'react-native';

let _AsyncStorage = AsyncStorage;
if (!_AsyncStorage) {
  _AsyncStorage = require('@react-native-async-storage/async-storage').default;
}

export default AsyncStorage;

You can also use this to check if an imported file exists using a try-catch block

try {
   require('./profile.png');
} catch (error) {
   console.log('Image was not found');
}

The try-catch(in the above code) checks and if the file we’re trying to import exists and then logs an output message without having to crash the app.

Conclusion

We have been able to learn how to safely import dependencies using our optional imports in Expo and React Native

Categories: React Native

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping Cart