Labs ICT
Pro Login

Component Lifecycle

What happens when a component mounts and unmounts.

Understanding Component Lifecycle

Every component in React Native goes through a lifecycle — it's created, it renders, it updates, and eventually it's destroyed. Understanding this lifecycle helps you know when to fetch data, set up subscriptions, clean up resources, and optimize performance.

In functional components, we manage the lifecycle using hooks like useEffect. This replaces the old class-based lifecycle methods like componentDidMount and componentWillUnmount.

The Mount Phase

The mount phase happens when a component is first created and displayed on screen. This is where you typically fetch initial data, set up timers, or subscribe to services.

import React, { useState, useEffect } from 'react';
import { View, Text, ActivityIndicator } from 'react-native';

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // This runs when the component mounts
    fetchUser(userId).then(data => {
      setUser(data);
      setLoading(false);
    });
  }, []); // Empty array means "run once on mount"

  if (loading) return <ActivityIndicator size="large" />;

  return (
    <View>
      <Text>{user.name}</Text>
    </View>
  );
}

The useEffect with an empty dependency array ([]) runs exactly once when the component mounts. This is where you put setup code that needs to run when the component first appears.

The Update Phase

Components re-render whenever their props or state change. This is the update phase. You can respond to specific changes using the dependency array in useEffect.

function MessageList({ conversationId }) {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    // This runs when conversationId changes
    loadMessages(conversationId).then(setMessages);
  }, [conversationId]); // Re-run when conversationId changes

  return (
    <View>
      {messages.map(msg => <Text key={msg.id}>{msg.text}</Text>)}
    </View>
  );
}

The dependency array tells React when to re-run the effect. If conversationId changes, the effect runs again with the new conversation. Without the dependency array, the effect would run on every render, which is usually not what you want.

The Unmount Phase

When a component is removed from the screen (like navigating away), it unmounts. You should clean up any resources you created during mount — cancel network requests, clear timers, unsubscribe from services.

function LiveChat() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const socket = connectToChat();

    socket.on('message', (msg) => {
      setMessages(prev => [...prev, msg]);
    });

    // Cleanup function - runs when component unmounts
    return () => {
      socket.disconnect();
    };
  }, []);

  return (
    <View>
      {messages.map((msg, i) => <Text key={i}>{msg}</Text>)}
    </View>
  );
}

The cleanup function is returned from useEffect. It runs when the component unmounts or before the effect runs again. This prevents memory leaks and ensures you don't have stale subscriptions or timers running after the component is gone.