React setState in useEffect causes infinite loop

Got asked this in a React interview. Couldn't answer it properly. 😔 "What happens when you call  setState inside useEffect?" I said: "State updates and  component re-renders." Interviewer: "That's incomplete." Here's the complete answer: When you call setState inside useEffect: 1. State updates 2. Component re-renders 3. useEffect runs again 4. If no dependency array —    infinite loop 💀 5. If deps array present —    runs only when deps change // ❌ Infinite loop useEffect(() => {  setCount(count + 1) }) // no dependency array! // ✅ Runs once useEffect(() => {  setCount(count + 1) }, []) // empty array // ✅ Runs when count changes useEffect(() => {  console.log(count) }, [count]) The interviewer then asked: "Why does React batch state updates?" That's a post for another day. 😄 Save this — it comes up  in almost every React interview. What React interview question  stumped you? Drop it below 👇 #ReactJS #JavaScript #Frontend #ReactInterview #WebDevelopment #InterviewPrep

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories