← Back to Chapters

useEffect Hook

⚛️ useEffect Hook

? Quick Overview

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.

? Key Concepts

  • Runs after component renders
  • Can depend on state or props
  • Supports cleanup logic
  • Replaces lifecycle methods

? Syntax / Theory

The useEffect hook takes two arguments: an effect function and an optional dependency array.

? View Code Example
// Basic structure of useEffect hook
useEffect(() => {
console.log("Effect executed");
}, []);

? Code Example(s)

? View Code Example
// 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>
);
}

? Live Output / Explanation

Each time the text is pressed, the count state updates. The useEffect hook runs again because count is in the dependency array.

1️⃣ Interactive Simulator: Dependencies

Adjust the state below to see when the Effect fires. The visual code block simulates how React watches the Dependency Array.

 
useEffect(() => {
  console.log("Effect Ran!");
}, [count]);
> Component Mounted. Effect Ran.

2️⃣ Interactive Simulator: Cleanup & Unmounting

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.

Status: Unmounted
> Ready to mount...
?
Component is Unmounted
No Timer Running

? Interactive Explanation

Think of useEffect as a watcher. Whenever the values in its dependency array change, React re-runs the effect logic automatically.

? Use Cases

  • Fetching API data
  • Listening to events
  • Running timers
  • Updating document or screen title

? Tips & Best Practices

  • Always define dependencies correctly
  • Use cleanup functions for subscriptions
  • Avoid unnecessary re-renders

? Try It Yourself

  1. Create a timer using setInterval inside useEffect
  2. Log messages when a component mounts and unmounts
  3. Fetch data from a public API