React App Freezes with Infinite Re-renders

My React app was freezing the browser completely. Chrome tab: "Page Unresponsive" 😱 After 2 hours of debugging I found this: const UserProfile = () => { const [user, setUser] = useState({}) // ❌ New object created every render // triggers useEffect infinitely! useEffect(() => { fetchUser().then(data => { setUser(data) }) }, [user]) // 👈 THIS is the problem return <div>{user.name}</div> } Can you spot the bug? 👇 The problem: 1. Component renders 2. useEffect runs → setUser({...}) 3. user state changes → re-render 4. useEffect runs again → setUser({...}) 5. Repeat forever 💀 The fix: const UserProfile = () => { const [user, setUser] = useState({}) // ✅ Empty array = run only once useEffect(() => { fetchUser().then(data => { setUser(data) }) }, []) // 👈 Fixed! return <div>{user.name}</div> } 3 rules to avoid infinite re-renders: → Never put state in useEffect deps if you're setting that same state inside → Empty [] = run once on mount → Always ask: "Does this dep actually need to be here?" 2 hours of debugging. 1 character fix. 😅 Have you hit this bug before? Comment below! 👇 #ReactJS #JavaScript #Frontend #WebDevelopment #ReactHooks #Debugging

  • text

this is a real case of a minor bug which can cause your hour of debugging. except you know how to use real ai tools. of if you know where the problem exist.

This is a common rookie mistake. What happens here is: When the state updates → React re-renders the component. Because this state is included in the useEffect dependency array → the effect runs again after the re-render. If the useEffect updates the same state again → it causes another re-render and the cycle keeps repeating.

Like
Reply

Please stop creating this AI generated garbage

I appreciate you breaking down the step-by-step process of identifying and solving the infinite re-render issue in React, it's a valuable reminder to carefully consider the dependencies in useEffect hooks.

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories