React useEffect with empty dependency array explained

𝐑𝐞𝐚𝐜𝐭 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 🤔 Many developers use useEffect daily… but fail to answer this. Question: What happens if dependency array is empty in useEffect? Example: useEffect(() => { console.log("Hello"); }, []); Answer 👇 When dependency array is empty [] ➡ useEffect runs only once ➡ It runs after first render ➡ It will NOT run again on state change Why? Because React thinks there are no dependencies to watch. Now tricky part ⚠️ useEffect(() => { console.log(count); }, []); If count changes, this will NOT run again. Because count is not in dependency array. Correct way ✅ useEffect(() => { console.log(count); }, [count]); Tip for React Interviews: Always remember — No dependency → runs every render Empty array → runs once With dependency → runs when value changes More React interview questions coming 🚀 #ReactJS #useEffect #FrontendDeveloper #JavaScript #WebDevelopment #CodingInterview #ReactInterview #NextJS #SoftwareDeveloper

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories