Pretraga

The Complete React Native Hooks Course [ FHD • HD ]

return <TextInput ref=inputRef placeholder="Auto-focused" />;

intervalRef.current = setInterval(() => setTimer(t => t + 1); , 1000);

Use these with React.memo to skip re-rendering child components. 6. useRef – Mutable References & DOM Access Goal: Store mutable values (don't trigger re-renders) or access native elements.

fetchData(); return () => abortController.abort(); , [url]); The Complete React Native Hooks Course

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();

if (loading) return <ActivityIndicator size="large" />; return ( <View> <Text>JSON.stringify(data)</Text> </View> );

State persists across re-renders; updating state triggers a re-render. 2. useEffect – Handling Side Effects Goal: Replace lifecycle methods ( componentDidMount , componentDidUpdate , componentWillUnmount ). fetchData(); return () =&gt; abortController

import useNavigation, useRoute, useFocusEffect from '@react-navigation/native'; function ProfileScreen() const navigation = useNavigation(); const route = useRoute(); const userId = route.params;

useEffect(() => let isMounted = true; // Prevents setting state if component unmounts

For complex state, combine with useReducer . Part 2: Additional Built-in Hooks 4. useReducer – Complex State Logic Goal: Manage state with reducers (predictable state updates). useEffect – Handling Side Effects Goal: Replace lifecycle

const fetchData = async () => try const response = await fetch('https://api.example.com/data'); const json = await response.json(); if (isMounted) setData(json); catch (error) console.error(error); finally if (isMounted) setLoading(false); ;

// 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]);

const addTodo = (text) => dispatch(addTodoAction(text));

import React, useState from 'react'; import View, Text, Button, TextInput from 'react-native'; export default function UserInput() const [name, setName] = useState(''); const [submitted, setSubmitted] = useState(false);

const initialState = count: 0, step: 1 ; function reducer(state, action) switch (action.type) case 'increment': return ...state, count: state.count + state.step ; case 'decrement': return ...state, count: state.count - state.step ; case 'setStep': return ...state, step: action.payload ; default: return state;