0
0
React-nativeHow-ToBeginner ยท 3 min read

How to Use useEffect in React Native: Simple Guide

In React Native, useEffect runs code after the component renders, letting you perform side effects like fetching data or updating the UI. You use it by passing a function and an optional dependency array to control when it runs.
๐Ÿ“

Syntax

The useEffect hook takes two arguments: a function to run after render, and an optional array of dependencies that control when the effect runs again.

  • Effect function: Code to run after render, like fetching data or setting up listeners.
  • Dependency array: List of values that trigger the effect to rerun when they change. If empty, effect runs once after first render.
javascript
useEffect(() => {
  // Your side effect code here
  return () => {
    // Cleanup code here (optional)
  };
}, [dependencies]);
๐Ÿ’ป

Example

This example shows a React Native component that uses useEffect to fetch data once when the component loads and display it.

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

export default function DataFetcher() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => {
        setData(json);
        setLoading(false);
      });
  }, []); // Empty array means run once on mount

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

  return (
    <View style={{ padding: 20 }}>
      <Text>Todo ID: {data.id}</Text>
      <Text>Title: {data.title}</Text>
      <Text>Completed: {data.completed ? 'Yes' : 'No'}</Text>
    </View>
  );
}
Output
Shows a loading spinner, then displays fetched todo item with ID, title, and completion status.
โš ๏ธ

Common Pitfalls

Common mistakes when using useEffect include:

  • Not providing a dependency array, causing the effect to run after every render and possibly causing infinite loops.
  • Including changing objects or functions in dependencies without memoization, causing unnecessary reruns.
  • Forgetting to clean up subscriptions or timers inside the effect, leading to memory leaks.
javascript
/* Wrong: effect runs every render causing infinite loop */
useEffect(() => {
  setCount(count + 1);
});

/* Right: run effect only once on mount */
useEffect(() => {
  setCount(count + 1);
}, []);
๐Ÿ“Š

Quick Reference

  • Run once on mount: use useEffect(() => { ... }, [])
  • Run on specific value change: include that value in dependency array
  • Cleanup: return a function inside effect to clean up
  • Avoid infinite loops: don't update state inside effect without dependencies
โœ…

Key Takeaways

useEffect runs side effects after component renders in React Native.
Provide a dependency array to control when the effect runs again.
Use an empty array to run effect only once on component mount.
Always clean up subscriptions or timers inside useEffect to avoid leaks.
Avoid updating state inside useEffect without proper dependencies to prevent infinite loops.