← Back to Chapters

useEffect Lifecycle

⚛️ useEffect Lifecycle

? Quick Overview

useEffect is a React Hook used in React Native to handle side effects such as API calls, subscriptions, timers, and lifecycle-related logic inside functional components. It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.

? Key Concepts

  • Runs after the component renders
  • Can run once, multiple times, or on cleanup
  • Controlled using a dependency array
  • Supports cleanup logic for unmounting

? Syntax / Theory

The useEffect hook accepts two arguments:

  • A callback function containing side-effect logic
  • An optional dependency array
? View Code Example
// Basic useEffect syntax
useEffect(() => {
  console.log("Effect executed");
}, []);

? Code Example(s)

? View Code Example
// useEffect running once on component mount
import React, { useEffect } from "react";
import { View, Text } from "react-native";

const App = () => {
  useEffect(() => {
    console.log("Component Mounted");
  }, []);

  return (
    <View>
      <Text>Hello React Native</Text>
    </View>
  );
};

export default App;

? Live Output / Explanation

What Happens?

When the component loads for the first time, the message "Component Mounted" is printed in the console. Because the dependency array is empty, the effect runs only once.

? Simulator 1: Basic Lifecycle

Click the buttons below to visualize how useEffect behaves when a component mounts, updates its state, and unmounts.

(Component Unmounted)
// Console Logs will appear here...

⚠️ Simulator 2: The Cleanup Trap (Memory Leaks)

If you start a Timer in useEffect but forget to clear it in the return function, the timer keeps running even after the component is removed. This is a Memory Leak.

(Timer Unmounted)
// Timer Logs will appear here...

? Interactive Lifecycle Mapping

? View Code Example
// Demonstrating mount, update, and unmount behavior
useEffect(() => {
  console.log("Mounted or Updated");

  return () => {
    console.log("Component Unmounted");
  };
}, [count]);

? Use Cases

  • Fetching data from APIs
  • Listening to events or subscriptions
  • Running timers or intervals
  • Updating document title or app state

? Tips & Best Practices

  • Always clean up subscriptions or timers
  • Use dependency arrays carefully
  • Split multiple effects into separate useEffect hooks
  • Avoid heavy logic inside a single effect

? Try It Yourself

  • Create a counter and log updates using useEffect
  • Fetch data from a public API
  • Implement cleanup using return function
  • Experiment with different dependency arrays