0PricingLogin
React Native Academy · Lesson

The useEffect Hook and Dependency Arrays

Understand when useEffect runs, control it with a dependency array, and clean up subscriptions or timers by returning a cleanup function.

What is useEffect?

useEffect lets function components perform side effects: fetching data, setting up subscriptions, manipulating the DOM, starting timers, or calling native APIs. Side effects cannot be run directly in the render function because renders must be pure. useEffect runs after the component renders to the screen.

import { useEffect } from 'react';

function App() {
  useEffect(() => {
    console.log('Component rendered');
    // Side effects go here
  });
}

The Dependency Array

The second argument to useEffect is the dependency array. React uses it to decide when to re-run the effect. If the dependency array is omitted, the effect runs after every render. If it is empty ([]), the effect runs once after the initial render. If it contains values, the effect re-runs whenever any of those values change.

// Runs after every render
useEffect(() => { ... });

// Runs once on mount
useEffect(() => { ... }, []);

// Runs on mount and whenever userId changes
useEffect(() => { ... }, [userId]);

All lessons in this course

  1. The useEffect Hook and Dependency Arrays
  2. Making GET Requests with Axios
  3. Handling Loading and Error States
  4. POST, PUT, and DELETE with Axios
← Back to React Native Academy