From the author of the Telegram channel REACT NATIVE HUB
Join a growing community of React Native Devs! 👆
When building React Native apps, there’s often a need to persist user preferences, tokens, or flags between sessions. While AsyncStorage is the go-to solution for persistent storage, interacting with it manually every time can get repetitive and messy.
Let’s fix that with a custom hook: useAsyncStorage
✅ Implementation using @react-native-async-storage/async-storage
:
import { useState, useEffect } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
function useAsyncStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(initialValue);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const loadValue = async () => {
try {
const item = await AsyncStorage.getItem(key);
setStoredValue(item != null ? JSON.parse(item) : initialValue);
} catch (error) {
console.error("Error loading from AsyncStorage", error);
} finally {
setIsLoading(false);
}
};
loadValue();
}, [key]);
const setValue = async (value) => {
try {
const valueToStore =
value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
await AsyncStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.error("Error setting AsyncStorage", error);
}
};
return [storedValue, setValue, isLoading];
}
export default useAsyncStorage;
🧪 Usage Example: Theme Toggle
import React, { useEffect } from "react";
import { View, Text, Button, StyleSheet } from "react-native";
import useAsyncStorage from "./useAsyncStorage";
const ThemeSwitcher = () => {
const [theme, setTheme] = useAsyncStorage("theme", "light");
const toggleTheme = () => {
setTheme((prev) => (prev === "light" ? "dark" : "light"));
};
return (
<View style={[
styles.container,
theme === "dark" ? styles.dark : styles.light,
]}
>
<Text style={styles.text}>Current Theme: {theme}</Text>
<Button title="Toggle Theme" onPress={toggleTheme} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
dark: {
backgroundColor: "#222",
},
light: {
backgroundColor: "#fff",
},
text: {
fontSize: 20,
marginBottom: 16,
},
});
export default ThemeSwitcher;
🧩 When to Use It?
You can apply useAsyncStorage in:
🌙 Theme or UI preferences
🔐 Authentication tokens
✅ Onboarding screens
📦 Offline saved content
etc…
Final Thoughts
Hooks like useAsyncStorage are about more than just reducing boilerplate — they help encapsulate logic and build scalable apps faster. Whether you’re working solo or in a team, abstracting persistence logic like this is a pro move.
About me: My name is Arsen, and I am a react native developer and owner of the TG channel 👇
🔗 Join TG community for React Native Devs: REACT NATIVE HUB
Top comments (0)