if (loading) return <ActivityIndicator size="large" />; return ( <View> <Text>JSON.stringify(data)</Text> </View> );
export default function AutoFocusInput() const inputRef = useRef(null); const intervalRef = useRef(null); const [timer, setTimer] = useState(0); useEffect(() => inputRef.current?.focus(); // Focus on mount
Goal: Extract component logic into reusable functions. Example: useFetch – Reusable data fetching // useFetch.js export function useFetch(url) const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => const abortController = new AbortController();
// Usage in component function UserList() const data, loading, error = useFetch('https://jsonplaceholder.typicode.com/users'); if (loading) return <ActivityIndicator />; if (error) return <Text>Error: error</Text>; return (/* render data */); The Complete React Native Hooks Course
useFocusEffect( useCallback(() => // Reload data when screen comes into focus loadUserData(userId); return () => console.log('Screen unfocused'); , [userId]) );
useEffect(() => let isMounted = true; // Prevents setting state if component unmounts
return () => isMounted = false; ; // Cleanup on unmount , []); // Empty array = run once after mount if (loading) return <
return ( <View> <TextInput placeholder="Enter your name" value=name onChangeText=setName style= borderWidth: 1, margin: 10, padding: 8 /> <Button title="Submit" onPress=() => setSubmitted(true) /> submitted && <Text>Hello, name!</Text> </View> );
export default function Counter() const [state, dispatch] = useReducer(reducer, initialState);
Goal: Memoize functions and values to prevent unnecessary re-renders. ActivityIndicator size="large" />
"plugins": ["react-hooks"], "rules": "react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "warn"
return () => clearInterval(intervalRef.current); , []);
// useCallback: memoizes the function itself const handlePress = useCallback(() => console.log('Button pressed', count); , [count]); // Re-create only when count changes // useMemo: memoizes the result of a computation const expensiveValue = useMemo(() => return heavyComputation(data); , [data]);