Pendahuluan
Yo developers! Udah pada tau belum sih pentingnya Custom Hooks di React Native? Nggak cuma bikin code kamu lebih rapi, tapi juga bikin development jadi lebih cepet dan efisien. Di artikel ini, gue bakal share 10 Custom Hooks yang bakalan bikin development lo naik level!
Kenapa Custom Hooks Penting?
- π― Reusable logic yang bisa dipake berkali-kali
- π¦ Code yang lebih terorganisir dan maintainable
- β‘ Performa aplikasi yang lebih optimal
- π οΈ Testing yang lebih mudah
1. useNetworkStatus
const useNetworkStatus = () => {
const [isConnected, setIsConnected] = useState(true);
useEffect(() => {
const unsubscribe = NetInfo.addEventListener(state => {
setIsConnected(state.isConnected);
});
return () => unsubscribe();
}, []);
return isConnected;
};
Buat apa sih? Hook ini berguna banget buat:
- Monitor koneksi internet user
- Handle offline state dengan smooth
- Kasih notif ke user kalo koneksi putus
2. useAppState
const useAppState = () => {
const [appState, setAppState] = useState(AppState.currentState);
useEffect(() => {
const subscription = AppState.addEventListener('change', nextAppState => {
setAppState(nextAppState);
});
return () => subscription.remove();
}, []);
return appState;
};
Perfect buat:
- Deteksi app lagi aktif atau di background
- Pause/resume operasi berdasarkan state
- Optimize resource usage
3. useKeyboard
const useKeyboard = () => {
const [keyboardHeight, setKeyboardHeight] = useState(0);
useEffect(() => {
const showSubscription = Keyboard.addListener('keyboardDidShow', (e) => {
setKeyboardHeight(e.endCoordinates.height);
});
const hideSubscription = Keyboard.addListener('keyboardDidHide', () => {
setKeyboardHeight(0);
});
return () => {
showSubscription.remove();
hideSubscription.remove();
};
}, []);
return keyboardHeight;
};
Mantep buat:
- Handle keyboard visibility
- Bikin animasi smooth pas keyboard muncul/ilang
- Adjust layout otomatis
4. usePermissions
const usePermissions = (permission) => {
const [hasPermission, setHasPermission] = useState(null);
useEffect(() => {
(async () => {
const { status } = await Permissions.askAsync(permission);
setHasPermission(status === 'granted');
})();
}, [permission]);
return hasPermission;
};
Keren buat:
- Request permission dengan elegant
- Track permission status
- Handle permission denial
5. useGeolocation
const useGeolocation = () => {
const [location, setLocation] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const watchId = Location.watchPositionAsync(
{
accuracy: Location.Accuracy.High,
timeInterval: 1000,
},
(position) => {
setLocation(position);
}
);
return () => {
watchId.then(id => id.remove());
};
}, []);
return { location, error };
};
Perfect buat:
- Track lokasi user real-time
- Background location updates
- Location-based features
6. useStorage
const useStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(initialValue);
useEffect(() => {
AsyncStorage.getItem(key)
.then(value => value ? JSON.parse(value) : initialValue)
.then(setStoredValue);
}, [key]);
const setValue = async (value) => {
await AsyncStorage.setItem(key, JSON.stringify(value));
setStoredValue(value);
};
return [storedValue, setValue];
};
Mantep buat:
- Persist data locally
- Cache management
- Offline-first features
7. useDeepLinking
const useDeepLinking = () => {
const [link, setLink] = useState(null);
useEffect(() => {
const getInitialURL = async () => {
const initialUrl = await Linking.getInitialURL();
setLink(initialUrl);
};
Linking.addEventListener('url', ({url}) => setLink(url));
getInitialURL();
return () => {
Linking.removeAllListeners('url');
};
}, []);
return link;
};
Berguna buat:
- Handle deep links
- Custom URL schemes
- App-to-app navigation
8. useAnimation
const useAnimation = (initialValue = 0) => {
const animatedValue = useRef(new Animated.Value(initialValue)).current;
const animate = (toValue, duration = 300) => {
Animated.timing(animatedValue, {
toValue,
duration,
useNativeDriver: true,
}).start();
};
return [animatedValue, animate];
};
Keren buat:
- Smooth animations
- Interactive UI elements
- Gesture responses
9. useDimensions
const useDimensions = () => {
const [dimensions, setDimensions] = useState(Dimensions.get('window'));
useEffect(() => {
const subscription = Dimensions.addEventListener('change', ({window}) => {
setDimensions(window);
});
return () => subscription?.remove();
}, []);
return dimensions;
};
Perfect buat:
- Responsive layouts
- Orientation changes
- Dynamic sizing
10. useBackHandler
const useBackHandler = (handler) => {
useEffect(() => {
const subscription = BackHandler.addEventListener('hardwareBackPress', handler);
return () => subscription.remove();
}, [handler]);
};
Mantep buat:
- Custom back behavior
- Prevent accidental exits
- Navigation management
Best Practices & Tips π₯
1. Performance Optimization
- Hindari re-renders yang nggak perlu
- Gunakan useMemo dan useCallback dengan bijak
- Optimize dependencies di useEffect
2. Error Handling
try {
// Your logic here
} catch (error) {
// Handle errors properly
console.error('Something went wrong:', error);
}
3. TypeScript Integration
interface HookProps {
initialValue: T;
options?: Record;
}
Troubleshooting Guide π οΈ
Common Issues:
- Memory leaks di useEffect
- Infinite re-renders
- Race conditions
Solutions:
- Selalu cleanup di useEffect
- Check dependencies array
- Use proper error boundaries
Kesimpulan
Custom Hooks ini bakal bikin development lo jadi lebih asik dan produktif! Jangan lupa:
- β Reuse code sebanyak mungkin
- β Test hooks secara terpisah
- β Dokumentasi yang jelas
- β Error handling yang proper
Keep coding and stay awesome! π