🛠️ Stop Making These Two Critical useEffect Mistakes!
Brief summary of my video about useEffect (generated by NotebookLM): The React useEffect Hook is essential for side effects like data fetching. But watch out for these two common traps that can lead to broken or buggy application behavior. 1. The Missing Dependency Trap Many developers use an empty dependency array ([]) to make useEffect run only once when the component mounts. The Problem: If your effect logic uses a state variable (like a Filter), but that variable is not included in the dependency array, the effect will not rerun when the state changes. React itself cannot automatically detect this dependency. You'll see the component re-render with the new state (e.g., 'Sale'), but the product list remains unchanged (e.g., still 'Popular' products 1, 2, 3). The Fix: Always provide an array containing all dependent values used within the effect's callback. By including the state variable Filter, React notices when the value changes, and the effect is correctly triggered again to fetch the updated data. Action Item: If your effect isn't running when you expect it to, check your Dependency Array first! 2. The async/await Trap A major error occurs when you try to declare the useEffect callback function itself as async. The Problem: The useEffect callback must return either nothing (undefined) or a cleanup function. An async function, however, implicitly returns a Promise. Since a Promise is not a valid cleanup function, React throws an error: "cleanup function must be a function or undefined". The Fixes (Keep the Outer Function Synchronous): 1. Use .then(): Avoid async/await and use the Promise API syntax with .then() to handle the asynchronous result. 2. Declare an Inner Function (Recommended): Define a separate, named async function (e.g., innerFetch) inside the useEffect callback. The outer useEffect callback remains synchronous and simply calls this inner function, successfully avoiding the implicit Promise return. --------------------------------------------------------------------------------