Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
useDirectorySync - syncs React Native directories (using react-native-fs) on appState change
import { useState } from 'react';
import useAppState from 'react-native-appstate-hook';
import RNFS from 'react-native-fs';
async function copyDir(source: string, destination: string) {
const fileChangeLog: string[] = [];
await copyDirRecursive(source, destination, fileChangeLog);
return fileChangeLog;
async function copyDirRecursive(source: string, destination: string, fileChangeLog: string[]) {
const items = await RNFS.readDir(source);
await RNFS.mkdir(destination);
await items.forEach(async (item) => {
if (item.isFile()) {
const destinationFile = `${destination}/${}`;
const fileExists = await RNFS.exists(destinationFile);
if (fileExists) {
const sourceFileHash = await RNFS.hash(item.path, 'md5');
const destinationFileHash = await RNFS.hash(destinationFile, 'md5');
if (sourceFileHash === destinationFileHash) return;
await RNFS.copyFile(item.path, destinationFile);
} else {
const sourceDir = `${source}/${}`;
const destinationDir = `${destination}/${}`;
await copyDirRecursive(sourceDir, destinationDir, fileChangeLog);
const useDirectorySync = (directorySource: string, directoryDestination: string) => {
const [directoryPath, setDirectoryPath] = useState('');
onForeground: async () => {
const filesChanged = await copyDir(directorySource, directoryDestination);
if (filesChanged.length)'FilesChanged', filesChanged);
return directoryPath;
export default useDirectorySync;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment