[JS] Why My React Component Is Re-Rendering Forever
Hey everyone 👋 お元気ですか?
Today I want to share something that once drove me crazy:
“Why is my React component re-rendering infinitely!?”
What You Can Expect from This Post
At first, I thought maybe it was a bug in React. But of course — it wasn’t React’s fault. It was mine 😅
Let me walk you through what happened, what I learned, and how to avoid falling into infinite re-render trap.
Infinite Re-renders Are Triggered
Let’s say you have a component that fetches some data and sets it into state:
const [data, setData] = useState([]);
fetch('/api/some-data')
.then(res => res.json())
.then(result => setData(result));
Seems totally fine, right?
But… once you run this component, your app freezes. The console explodes. Your fans start spinning.
You’re stuck in an infinite re-render loop.
Why Does This Cause Infinite Re-renders?
Here’s what’s happening under the hood:
- Component renders.
fetch()runs, and when data comes back, it callssetData.- State updates → React triggers a re-render.
- The whole component runs again, including
fetch()andsetData. - Repeat. Forever.
Because fetch() is directly called in the component body (outside useEffect), it runs on every render.
Each time it runs, it triggers another state update, which causes another render... and so on.
Use useEffect As Your Solution!
React provides useEffect for a reason — to run side effects after rendering, and only when needed.
Here’s the fixed version:
useEffect(() => {
fetch('/api/some-data')
.then(res => res.json())
.then(result => setData(result));
}, []); // empty dependency array = run only once on mount
Now, fetch() only runs once — right after the component mounts — and it won’t re-run unless one of the dependencies in the array changes (in this case, there are none).
What’s a "Side Effect" Anyway?
In React, anything that affects something outside the component is a side effect:
- Fetching data
- Setting a timer
- Manually changing the DOM
- Subscribing to events
These should always go inside useEffect.
If you put them directly in the render body, React will keep doing them every single time the component re-renders — and that’s where the infinite loop monster comes in.
Conclusion
If you’re doing something that isn’t pure — like fetching data, setting timers, subscribing to listeners — put it in useEffect.
Otherwise, your component might re-render again and again… and again.
So next time you hit an infinite loop, don’t panic.
Check your useEffect — it might just save your app (and your sanity).
じゃ、またね!
Comments ()