The Complete React Native Hooks Course -

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;

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(() => let isMounted = true; // Prevents setting state if component unmounts

// 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]); The Complete React Native Hooks Course

Goal: Memoize functions and values to prevent unnecessary re-renders.

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

fetchData(); return () => abortController.abort(); , [url]); const initialState = count: 0, step: 1 ;

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

useFocusEffect( useCallback(() => // Reload data when screen comes into focus loadUserData(userId); return () => console.log('Screen unfocused'); , [userId]) );

export default function Counter() const [state, dispatch] = useReducer(reducer, initialState); useEffect(() =&gt; let isMounted = true; // Prevents

export default function AutoFocusInput() const inputRef = useRef(null); const intervalRef = useRef(null); const [timer, setTimer] = useState(0); useEffect(() => inputRef.current?.focus(); // Focus on mount

return items, loadMore, loading, hasMore ;

// 3. Consume in any child function ThemedComponent() const theme = React.useContext(ThemeContext); return <Text style= color: theme === 'dark' ? 'white' : 'black' >Hello</Text>;

return () => clearInterval(intervalRef.current); , []);