useEffect is a core React Hook used in React Native to handle side effects such as API calls, subscriptions, timers, and updating the UI after state changes.
The useEffect hook takes two arguments: an effect function and an optional dependency array.
// Basic structure of useEffect hook
useEffect(() => {
console.log("Effect executed");
}, []);
// Counter example using useEffect
import React, { useState, useEffect } from "react";
import { View, Text } from "react-native";
export default function App() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Count changed:", count);
}, [count]);
return (
<View>
<Text onPress={() => setCount(count + 1)}>
Count: {count}
</Text>
</View>
);
}
Each time the text is pressed, the count state updates. The useEffect hook runs again because count is in the dependency array.
Adjust the state below to see when the Effect fires. The visual code block simulates how React watches the Dependency Array.
The Cleanup Function is crucial for preventing memory leaks (like clearing intervals or event listeners). It runs when the component unmounts (disappears) or before the effect re-runs.
Think of useEffect as a watcher. Whenever the values in its dependency array change, React re-runs the effect logic automatically.
setInterval inside useEffect