Effects and Their Dependencies
Omitting the second argument to useEffect()
causes the effect function (the first argument) to execute after every component function execution. Providing an empty array causes the effect function to run only once (after the first component function invocation). But is that all you can control?
No, it isn't.
The array passed to useEffect()
can and should contain all variables, constants, or functions that are used inside the effect function—if those variables, constants, or functions were defined inside the component function (or in some parent component function, passed down via props).
Consider this example:
import { useState, useEffect } from 'react'; import classes from './BlogPosts.module.css'; const DEFAULT_URL = 'https://jsonplaceholder.typicode.com/posts'; async function fetchPosts(url) { const response = await fetch(url); const blogPosts = await response.json(); ...